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

发布于 2024-12-09 12:14:02 字数 600 浏览 1 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鲜肉鲜肉永远不皱 2024-12-16 12:14:02

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

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

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

但您可能不关心完整的 absoluteURL,在这种情况下我建议:

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

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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文