Webpage js, webpage js
Communication between JS and iOS mainly uses two methods: (The PhoneGap framework is also based on this principle)
1. stringByEvaluatingJavaScriptFromString method of UIWebView
2. UIWebViewDelegate
-(BOOL) webView :( UIWebView *) webView shouldStartLoadWithRequest :( NSURLRequest *) request navigationType :( UIWebViewNavigationType) navigationType Method
Example:
The previous part is a UIWebView that implements UIWebViewDelegate.
- -(Void) viewDidLoad
- {
- [Super viewDidLoad];
- NSString * path = [[NSBundle mainBundle] pathForResource: @ "jm/info" ofType: @ "html"];
- NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL fileURLWithPath: path];
- [Self. webView loadRequest: request];
- }
- # Pragma mark-UIWebViewDelegate
- -(BOOL) webView :( UIWebView *) webView shouldStartLoadWithRequest :( NSURLRequest *) request navigationType :( UIWebViewNavigationType) navigationType
- {
- If ([request. mainDocumentURL. relativePath isw.tostring: @ "/getInfo/name"])
- {
- NSString * info = [[UIDevice currentDevice] name];
- NSString * js = [NSString stringWithFormat: @ "showInfo (\" name \ ", \" % @ \ ")", info];
- [Self. webView stringByEvaluatingJavaScriptFromString: js];
- Return false;
- }
- If ([request. mainDocumentURL. relativePath isEqualToString: @ "/getInfo/systemVersion"])
- {
- NSString * info = [[UIDevice currentDevice] systemVersion];
- NSString * js = [NSString stringWithFormat: @ "showInfo (\" systemVersion \ ", \" % @ \ ")", info];
- [Self. webView stringByEvaluatingJavaScriptFromString: js];
- Return false;
- }
- Return true;
- }
JS Code:
- <! DOCTYPE html>
- <Html>
- <Head>
- <Title> city </title>
- <Meta charset = "UTF-8">
- <Meta name = "viewport" content = "width = device-width, initial-scale = 1">
- <Link rel = "stylesheet" href = "jquery.mobile-1.0.css"/>
- <Script type = "text/javascript" src = "jquery. js"> </script>
- <Script type = "text/javascript" src = "jquery. mobile-1.0.js"> </script>
- <Script>
- Function getInfo (name)
- {
- Window. location = "/getInfo/" + name;
- }
- Function showInfo (id, info)
- {
- $ ("P #" +id).html (info );
- }
- </Script>
- </Head>
- <Body>
- <Div data-role = "page">
- <Div data-role = "content">
- <H2> Divice Info
- <Div data-role = "collapsible-set" data-theme = "c" data-content-theme = "d">
- <Div data-role = "collapsible">
- <H3 onclick = "getInfo ('name')"> name
- <P id = "name"> </p>
- </Div>
- <Div data-role = "collapsible">
- <H3 onclick = "getInfo ('systemversion')"> systemVersion
- <P id = "systemVersion"> </p>
- </Div>
- </Div>
- </Div>
- </Div>
- </Body>
- </Html>