0

I am building a Chrome extension and I'm facing some troubles while trying to overwrite some JavaScript events on the page the extension is going to run on.

I've built a mockup page with HTML that looks like so:

document.querySelector('#f').onclick = function() {
  document.body.innerHTML += 'you clicked';
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <button id='f'>click me</button>
</body>

</html>

The extension is supposed to change the onclick event. So here we have the content script:

document.querySelector('#f').onclick = function() {
  document.body.innerHTML += 'it is the extension';
}

But instead both of the functions are executed independently from each other - The innerHTML added when you click on the button is you clickedit is the extension. Why are both functions executed and how can i solve this issue?

Thanks in advance.

gamer_294
  • 13
  • 4

1 Answers1

0

Your script runs on a different context than the scripts that run in the page's context.

As stated on MDN:

content scripts get a "clean" view of the DOM. This means:

  • Content scripts cannot see JavaScript variables defined by page scripts.
  • If a page script redefines a built-in DOM property, the content script sees the original version of the property, not the redefined version

So actually your code doesn't redefine the onClick property, rather it adds an event listener, so you need to make your script run as a "page script" by injecting it into a <script> element.

A possible solution using a utility I've built for that purpose:

await runInPageContext(() => {
  document.querySelector('#f').onclick = function() {
    document.body.innerHTML += 'it is the extension';
  }
});

Arik
  • 5,266
  • 1
  • 27
  • 26