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? –
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:Now you can set a breakpoint in Xcode after your call to
stringByEvaluatingJavaScriptFromString:
. An error message might be available if you runIn 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 inshouldStartLoadWithRequest
is correct. InshouldStartLoadWithRequest
the page hasn't been loaded yet, and any state you introduce at that point will be discarded by the loading page.