Question

For example, I want to run this part of code every time user click a new link in my UIWebView,

NSString* js =
@"var meta = document.createElement('meta'); "
"meta.setAttribute( 'name', 'viewport' ); "
"meta.setAttribute( 'content', 'width = device-width;initial-scale=1.0; maximum-scale=1.0' ); "
"document.getElementsByTagName('head')[0].appendChild(meta)";

[webView stringByEvaluatingJavaScriptFromString: js];

how can I do that? which API should I look at? And I want this JS run in new page. How should I determine if the new page is fully loaded? –

Was it helpful?

Solution

There are two things likely to go wrong in this scenario: 1) your Js throws an exception and 2) the page reloads after your Js has run, and therefore reset the effects of your script.

In my experience, when a Javascript doesn't seem to run in a UIWebView, it's almost always the Javascript that is throwing an exception.

Try surrounding the script in try { ... } catch { ... } to capture the exception:

NSString* js =
@"try {"
"var meta = document.createElement('meta'); "
  // [rest of the script...]
"document.getElementsByTagName('head')[0].appendChild(meta)";
" } catch (exc) { "
" window.ERR = exc.toString(); "
" } "

Now you can set a breakpoint in Xcode after your call to stringByEvaluatingJavaScriptFromString:. An error message might be available if you run

po [webView stringByEvaluatingJavaScriptFromString:@"window.ERR"]

In your debug prompt.

A good idea when you try out Javascript on your UIWebView is to first do exploratory work in something like the Chrome Developer Tools to weed out the worst errors (e.g. syntax errors). If your code works there, the next step is to connect to the view using Safaris Web inspector for iOS and see if it still does what it should.

@nilveryboring's point that you add scripts in webViewDidFinishLoading rather than in shouldStartLoadWithRequest is correct. In shouldStartLoadWithRequest the page hasn't been loaded yet, and any state you introduce at that point will be discarded by the loading page.

OTHER TIPS

You can detect when the user clicks a link with:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

Once you have detected that he has clicked on a link, perform your js.

More on it in the Docs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top