Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Inside your html code use this snippet:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; function iOSNativeBridge(){ this.sendRawMessageToiOS = function(message){ // alert(message); console.log("Message string to iOS: [" + message+ "]"); var iframe = document.createElement("IFRAME"); iframe.setAttribute("src", "jscall://" + message); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; }; } bridge = new iOSNativeBridge(); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="javascript:bridge.sendRawMessageToiOS('your message');"&gt;link&lt;/a&gt; &lt;input type="button" value="button val" name="button" id="1" onClick="javascript:bridge.sendRawMessageToiOS('your message');"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>on native side, in uiwebview's delegate method:</p> <pre><code>- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *jsCallPrefix = @"jscall://"; NSString *fullURLRequested = request.URL.absoluteString; BOOL isJavaScriptCall = ([fullURLRequested hasPrefix:jsCallPrefix]); if (isJavaScriptCall) { NSString *messageConveyed = [fullURLRequested substringFromIndex:jsCallPrefix.length]; NSLog(@"Your message was: %@", messageConveyed); return NO; } return YES; } </code></pre> <p>With regards to the code on web side - I don't juggle with this dynamically created iframe without a reason. At first glance, it would seem sufficient just to change the location on webview's page (call document.location.href = "jscall://message"). The worst thing is, that is actually seems to work great. Unfortunately, if you take this shortcut, JS timers are messed up greatly. So take my advice - use this little, weird-looking, but <em>working</em> without any side-effects "sendRawMessageToiOS" as is :)</p> <p>Little more in-depth description of what's going on in the above code: In the web-code, whenever I want to push some data to the native-side of my app, I call sendRawMessageToiOS(dataInStringToSend). It creates an iframe, adds it to the DOM tree and sets it's location to be "jscall://" + dataInStringToSend Then, as expected, the uiwebview's delegate is asked, whether or not I'm willing to start the request to download a content from a given address. I check if it's actual address (and return YES then) or only this masquerade with special "jscall://" prefix. If it is this special call, I read data that's conveyed with it, and respond NO (because webview should not try to start any real request).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload