2

I am trying to make a chrome extension that can edit and remove parts of Javascript of a webpage preferably before the page is loaded.

For Example, the following script tag is within my test html website.

<script>
document.addEventListener("visibilitychange", onchange);
function onchange(){
    console.log('left');
}
</script>

This code tells the console when the user switches tabs. I would like to be able to edit this specific code only to prevent this from happening. Can I modify the text of JavaScript before runtime?

Brandalf
  • 476
  • 1
  • 6
  • 20

1 Answers1

1

You cant modify the code before runtime but you can remove the event listener.

removeEventListener("visibilitychange", onchange);

Note: You technically can edit JS before it's executed in Chrome using LocalOverrides however it requires you to have your devtools open on page load.

cam
  • 3,179
  • 1
  • 12
  • 15
  • Good suggestion but when I run it within the extension, it has no effect on the website, I assume it's because it can't access the onchange function. Any advice? Would it be possible just to edit the html text directly? – Brandalf Mar 30 '22 at 05:11
  • See [page context](/a/9517879), but there's probably a better solution: add your own listener (without using the page context trick) with `true` for the third param of addEventListener, then call event.stopPropagation(). – wOxxOm Mar 30 '22 at 05:49