Leslie Wu
Leslie Wu

Reputation: 770

window.postMessage behaves abnormal on Chrome extension

I use window.postMessage in Chrome Extension Content script:

function() {
   window.addEventListener("message", function(event) {
        console.log(event);
   }, false);


   window.postMessage({ type: \"FROM_PAGE\"}, "*");}

The abnormal behavior is that the first time I call this function, console print event once; the second time I call, console print twice; the third time, three times.
What's wrong with my code?

Upvotes: 0

Views: 655

Answers (1)

Moritz Roessler
Moritz Roessler

Reputation: 8611

This is because you are adding a new EventListener each time you call the function.

Thus every of your added EventListener's receives the Message posted by postmessage and then does

console.log(event)

So the first time you call you function. You EventListeners function,gets executed only once because only 1 EventListener is attached to the DOM that calls console.log

On the second time there are two EventListeners that execute console.log and so on...

You should attach you EventListener

window.addEventListener("message", function(event) {
...
}

outside your function.
And do only the window.postMessage({ type: \"FROM_PAGE\"}, "*"); part inside the function

Upvotes: 2

Related Questions