简体   繁体   中英

How to perform javascript only on certain URLS in a UIWebView

In my webViewDidFinishLoad method inside the UIWebViewController I have been trying to separate javascript calls so that they will only be performed on certain URLS. So far I have been trying a simple if statement that takes the current URL and tries to match the two strings. This is however not allowing the if statement to run despite the urls matching. Any help would be appreciated.

NSString *currentURL = homePage.request.URL.absoluteString;   

if (currentURL == @"www.google.com"){
    NSLog(@"hi");
[webView stringByEvaluatingJavaScriptFromString:injectedEmail];
[webView stringByEvaluatingJavaScriptFromString:injectedPassword];

[homePage stringByEvaluatingJavaScriptFromString:@"var field = document.getElementById('loginSubmit');"  
 "document.forms[0].submit();"];
}

You should take a look at NSURL Class Reference , which will tell you that -(NSString *)absoluteString returns an RFC 1808 absolute URL . These animals look like http://www.google.com/search?q=NSURL , and don't have just a host name.

Also, when you're comparing strings in Objective-C, using == will compare the string pointers , not the strings . You should be using something like:

if ([currentURL isEqualToString:@"http://www.google.com"]) {
    // do stuff
}

But you may not care about the complete absoluteURL , in which case I would suggest:

if ([currentURL hasPrefix:@"http://www.google.com"]) {
    // do stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM