UIWebView: Can I disable the javascript alert() inside any web page?

前端 未结 4 1985
情深已故
情深已故 2020-12-14 19:27

I am using UIWebView to load a URL.

Inside the page of that URL, it uses alert(\"whatever msg\") as JavaScript. My UIWebView w

相关标签:
4条回答
  • 2020-12-14 19:40

    Add this after your web view has loaded its content

    [MyWebView stringByEvaluatingJavaScriptFromString:@"window.alert=null;"];
    
    0 讨论(0)
  • 2020-12-14 19:47
    let script = """
                    window.alert=window.confirm=window.prompt=function(n){},
                    [].slice.apply(document.querySelectorAll('iframe')).forEach(function(n){if(n.contentWindow != window){n.contentWindow.alert=n.contentWindow.confirm=n.contentWindow.prompt=function(n){}}})
                    """
        webView.evaluateJavaScript(script, completionHandler: nil)
    
    0 讨论(0)
  • 2020-12-14 19:53

    You can bind window.alert to another function. So:

    window.alert = function() {
      //does nothing so effectively "disables" alert
    };
    

    Make sure you do this before you call any alerts. The neat thing about this is you can customize the way you display messages to the user. So you could override window.alert to log to the console (for debugging purposes) or you can render it on the page (with a lightbox or something similar).

    0 讨论(0)
  • 2020-12-14 19:56

    Since a UIWebView translates all Javascript alerts into native UIAlertViews it is fairly simple to block it on the native end. Looking into UIAlertView.h there is only one public method for showing an alert which is conveniently called: - (void)show;.

    @interface UIAlertView (Blocker)
    @end
    
    #import "UIAlertView+Blocker.h"
    
    @implementation UIAlertView (Blocker)
    
    - (void)show {
       return;
    }
    @end
    

    You can find the answer here: https://stackoverflow.com/a/21698251/2377378

    0 讨论(0)
提交回复
热议问题