Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `console.log` inside of a Worker in Chrome prints the same message twice

Pretty much what the title says. What is weirder is that this only happens when you run the program in a new tab, if you merely refresh the page, there will be only one message for each console.log.

Here is main.js:

const worker = new Worker('worker.js');

Here is worker.js:

console.log('Foo bar!');

Here is index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Web Workers</title>

<style></style>
</head>
<body>

<script src="main.js"></script>
</body>
</html>

The same is not happening in Firefox. I am using Chrome version 65, what's more odd is that the duplicate message seems to belong to no contexts listed in the "contexts" dropdown, so the only message listed when I try to filter out all console messages aside from ones sent by worker.js is the first message, the second message (the duplicate) seems to belong to no contexts.

@bean's answer revealed that there is already a question like this asked (from February 2018, I believe) which has not been answered. If no one answers this question either, I will consider raising an issue in Chrome's development forum/whatever.

like image 451
doubleOrt Avatar asked Apr 04 '18 20:04

doubleOrt


People also ask

How do I see console output in Chrome?

Console Logs in Chrome: In Google Chrome, the Console Logs are available as a part of Chrome Dev Tools. To open the dedicated Console panel, either: Press Ctrl + Shift + J (Windows / Linux) or Cmd + Opt + J (Mac).

How do I print my console log browser?

You should use the console. log() method to print to console JavaScript. The JavaScript console log function is mainly used for code debugging as it makes the JavaScript print the output to the console. To open the browser console, right-click on the page and select Inspect, and then click Console.

How do I debug shared Chrome?

For shared worker, you would need to go to chrome://inspect/#workers. Select "Shared workers" on the left panel. You would be able to see a list of shared workers if you have any running. You can click "inspect", which will open a new console for you to debug.


1 Answers

This seems to be a strange behavior in Chrome, and someone has posted the same issue here Console.log double logging from web workers.

However, placing console.log directly inside worker.js is not a good practice. A web worker runs in a separate thread and listens to the messages posted from main.js and take actions accordingly, thus any business logic should be placed inside the onmessage event handler. By doing this, you don't have to worry about code being executed twice.

like image 51
bean Avatar answered Oct 23 '22 02:10

bean