I have a WebView, and I want to call a view in Objective-C from JavaScript. Does someone know how I can do this?
I have this code in my ViewController:
The window.location method of calling objective c from JS isn't recommended. One example of problems: if you make two immediate consecutive calls one is ignored (since you can't change location too quickly) - try it yourself..
I recommend the following alternative approach:
function execute(url)
{
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", url);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
You call the execute
function repeatedly and since each call executes in its own iframe, they should not be ignored when called quickly.
Credits to this guy.
The standard workaround for UIWebView
is to set a UIWebViewDelegate
, and implement the method webView:shouldStartLoadWithRequest:navigationType:. In your JavaScript code, navigate to some fake URL that encodes the information you want to pass to your app, like, say:
window.location = "fake://myApp/something_happened:param1:param2:param3";
In your delegate method, look for these fake URLs, extract the information you need, take whatever action is appropriate, and return NO
to cancel the navigation. It's probably best if you defer any lengthy processing using some flavor of performSelector.