简体   繁体   中英

try to catch a warning in javascript

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. 

sounds like a good "warning" like "Nothing worked - just warning you. No errors, really."

Chromium pros who added this: https://src.chromium.org/viewvc/blink/trunk/Source/core/dom/Document.cpp?r1=164310&r2=164309&pathrev=164310

try catch won't help with a warning as I've tested, so is there a good way to detect this error as soon as possible?

what exactly does hasInsertionPoint want to be true? sometimes document.write works fine but not others. (it runs from my userscript on document-start and finding some things, don't ask to fix that or not use document.write - thread is not about that)

Sorry being so late, but for those who didn't find a good/correct answer or way of doing it, you can just replace the console.warn function, it's far away from a correct form of doing this, but it's the only work around I have managed to think/find so far...

Example:

function myCustomWarn(...args){

  //Example - Customize for your needs...
  var messages = args.filter(e => typeof e == 'string');

  for(m in messages){
    if(messages[m].indexOf('The warning I am looking for...') != -1){
      //treat the warning as you want
      //you could use switch case if you want
    };
  };

  return console.oldWarn(...args);

};

console.oldWarn = console.warn;

console.warn = myCustomWarn;

Remember that this "work around" only works if this code is evaluated at first, before that any possible warning can be thrown. Otherwise it may miss warnings thrown by any code that is executed first or before it.

@Marco Silva answer isn't perfect, he is using ES6 stuffs which are not supported everywhere. I think a debugger should be always as low level and portable as possible. This would allows you to avoid the situation where you own debugger is buggy.

Here is a code more portable:

function myCustomWarn(){
    var args = Array.prototype.slice.call(arguments);
    var messages = args.filter(function(a) {
        return typeof a == 'string';
    });


    for(var m in messages){
        alert(messages[m]);
    };

    /**
     *  Calling console.oldWarn with previous args seems to lead to a
     *  infinite recurvise loop on iOS. Not sure why, disabled. 
     *  then again, if you show your log message in alert why would you
     *  post them to console ? 
     */

    // return console.oldWarn(arguments);
};

console.oldWarn = console.warn;

console.warn = myCustomWarn;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM