Ignore javascript syntax errors in a page and continue executing the script

前端 未结 11 852
日久生厌
日久生厌 2020-12-02 18:21

I develop plugins for WordPress. It uses some jquery in the user side (themes) as a jquery plugin. The problem is, when there is an javascript error with other plugins made

相关标签:
11条回答
  • 2020-12-02 18:47

    What about window.onerror?

    https://developer.mozilla.org/en-US/docs/DOM/window.onerror

    0 讨论(0)
  • 2020-12-02 18:49

    Try :

    window.onerror = function(){
       return true;
    }
    

    That is if you can include this before the bugged script has been executed.

    0 讨论(0)
  • 2020-12-02 18:53

    I encountered the same problem: There are a bunch of plugins out there that make too many assumptions and cause JavaScript errors on YOUR page, even when you are being a good citizen; these errors have nothing to do with your plugin.

    There's no sense trying to handle errors in other plugins -- IMO it is better to be self-contained but resilient to their errors.

    In my case, the errors were halting the jquery DOM ready event, and my JavaScript init code wasn't getting executed. The exact form of the error isn't important though -- the solution is just to fire on multiple events.

    The solution for me was to have fallbacks in addition to relying on the jQuery DOM ready event:

    1. I wrapped any code I wanted to fire on the DOM ready event into their own function -- e.g. my_hardened_init_action();
    2. I added a function, my_hardened_init(), that only runs once. It calls my_hardened_init_action() the first time it is called, and does nothing on subsequent calls.
    3. I added various methods to call my_hardened_init() in the WordPress footer. In my case, I only needed two. First, trying the usual jQuery DOM init, but falling back to a simple setTimeout(). So if the jQuery DOM init never fires due to broken JavaScript, the timeout will fire shortly after when the page has finished loading.

    You could add multiple other fallbacks -- even add the code to the header if needs be. As my_hardened_init() only runs once, you can try as many times as you like to trigger it.

    This has worked on a bunch of client sites with a range of other broken plugins.

    Hope this helps.

    0 讨论(0)
  • 2020-12-02 18:55

    Put your call to plugin in

    try{
      ......
    }
    catch(e){
    
    }
    
    0 讨论(0)
  • 2020-12-02 18:58

    You should correct the old JavaScript error because it may create many problems, not for right now but for next time.

    Put your JavaScript file / code at the top (before JS having error), and call it before JavaScript effected by other JavaScript code.

    In case you need handle JavaScript exception at run time, best option is

    try { /* run js code */ } 
        catch (error){ /* resolve the issue or bug */ }
    
    0 讨论(0)
提交回复
热议问题