如何仅在UIWebView中的某些URL上执行javascript

时间:2021-12-02 00:19:02

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.

在UIWebViewController里面的webViewDidFinishLoad方法中,我一直试图分离javascript调用,以便它们只在某些URL上执行。到目前为止,我一直在尝试一个简单的if语句,它接受当前的URL并尝试匹配这两个字符串。但是,尽管url匹配,但这不允许if语句运行。任何帮助,将不胜感激。

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();"];
}

1 个解决方案

#1


1  

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.

您应该看看NSURL类参考,它将告诉您 - (NSString *)absoluteString返回RFC 1808绝对URL。这些动物看起来像http://www.google.com/search?q=NSURL,并且没有主机名。

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

此外,当您在Objective-C中比较字符串时,使用==将比较字符串指针,而不是字符串。你应该使用类似的东西:

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

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

但你可能不关心完整的绝对URL,在这种情况下我会建议:

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

#1


1  

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.

您应该看看NSURL类参考,它将告诉您 - (NSString *)absoluteString返回RFC 1808绝对URL。这些动物看起来像http://www.google.com/search?q=NSURL,并且没有主机名。

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

此外,当您在Objective-C中比较字符串时,使用==将比较字符串指针,而不是字符串。你应该使用类似的东西:

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

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

但你可能不关心完整的绝对URL,在这种情况下我会建议:

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