0

In my chrome extension's content script following code is not working:

var myFunction = () => {
  console.log("sending msg");
  chrome.runtime.sendMessage({ action: "myAction" });
}

But when I convert the arrow function to classic JS function it worked.

function myFunction() {
  console.log("sending msg");
  chrome.runtime.sendMessage({ action: "myAction" });
}

Why arrow function is not working?

miniature
  • 42
  • 6

1 Answers1

1

I guess you have a hoisting issue. A regular function call can be anywhere in the code while const myFunction = ... is only callable after its declaration.

Example of working code:

myFunction();

function myFunction() {
  console.log('Yay');
}

Example of failing code:

myFunction(); // TypeError, myFunction is undefined at this point

var myFunction = () => console.log('Yay');
Guerric P
  • 20,579
  • 2
  • 28
  • 66