简体   繁体   中英

Debugging Web Workers in Safari Web Inspector

Chrome's Dev Tools are great for debugging web workers as I can "browse" into that JavaScript environment and set break points. Even the console works as expected.

On Safari, it is a completely different story. console.log from the web worker doesn't even print in the console. I see the worker script loaded and I put a break point on it, but it doesn't break. I don't even see the scripts that were loaded with importScripts .

How can I use Safari's Web Inspector to troubleshoot problems?

Not that I think it matters, but I'm using Safari 8.

Insert the debugger; code in your source

Usage: Insert it anywhere you want to add a breakpoint and when developer console is open automatically execution will pause at that line

var a = 50;
a = a + 5;
debugger; //--> execution is paused here
a = a - 5;

For more info see the Debugger Documentation on mozilla.org

In lieu of console.log, you can use postMessage. postMessage should allow you to send debug messages to the safari console.

Here is a great example on how to do that, I pasted the main idea below:

//
// In the Main thread
//
var worker = new Worker('/path/of/webworker/code.js')
worker.onmessage = function (e) {
  var result = JSON.parse(e.data);
  if(result.type == 'debug') {
    console.log(result.msg);
  } else if(result.type == 'response') {
    // ... use result.answer ...
  }
}


//
// In the WebWorker
//
function debug(msg) {                                                           
  postMessage(JSON.stringify({type:'debug',msg:msg}));                          
}

onmessage = function (e) {
  var inputData = e.data;
  // work on input data
  debug('Working OK');
  // work some more
  // ...
  postMessage(JSON.stringify({type:'response', answer:42}));
};

If you don't want to play around with postMessage though, David Flanagan made a wrapper for it here that should allow you to at least do debugging with console.log

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