【问题标题】:iOS objective-c How can I catch window.open event in UIWebViewiOS objective-c 如何在 UIWebView 中捕获 window.open 事件
【发布时间】:2017-12-13 22:00:54
【问题描述】:

我正在开发由 Objective-C 编码的 iOS 混合应用程序。我想在 UIWebView 中捕获“window.open”事件。我找到了这段代码。

    -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
        if (navigationType == UIWebViewNavigationTypeLinkClicked ){       
           NSLog(@"opening link");
              return NO;
         }
    ....
    ...
        return YES;
    }

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        NSString * test =  [webView stringByEvaluatingJavaScriptFromString:@"window.open = function (open) { return function  (url, name, features) { window.location.href = url; return window; }; } (window.open);"];
        //
            NSLog(@"test:%@", test);   << always print blank
    ....
    ...
    ..
    }



info.plist
<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

但它不仅会捕获“window.open”,还会捕获其他链接事件。有些答案建议使用'stringByEvaluatingJavaScriptFromString',但我不明白。

你能解释一下让初学者容易理解吗?我只想在 UIWebView 中捕获“window.open”事件。

【问题讨论】:

    标签: ios objective-c iphone uiwebview window.open


    【解决方案1】:

    您需要使用以下代码来检测窗口打开:

    [webView stringByEvaluatingJavaScriptFromString:@"window.open = function (open) { return function  (url, name, features) { window.location.href = url; return window; }; } (window.open);"];
    

    尝试将上面的代码放在委托方法下面:

    - (void)webViewDidFinishLoad:(UIWebView *)webView {}
    

    【讨论】:

    • 我是这样写的。 NSString * test = [webView stringByEvaluatingJavaScriptFromString:@"window.open = function (open) { return function (url, name, features) { window.location.href = url; return window; }; } (window.open);" ];但是'test'总是返回空白(“”)你能告诉我更多吗?
    • 该代码有效吗?或者你想要解释吗?
    • 你把这段代码放在哪里?在什么函数里面?
    • - (void)webViewDidFinishLoad:(UIWebView *)webView { NSString * test = [webView stringByEvaluatingJavaScriptFromString:@"window.open = function (open) { return function (url, name, features) { window .location.href = url; 返回窗口; }; } (window.open);"]; // NSLog(@"test:%@", test);
    • 看起来你写的每件事都是正确的。如果未添加,您能否将以下代码放入 info.plist 中? NSAppTransportSecurityNSAllowsArbitraryLoads
    猜你喜欢
    • 2015-09-20
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多