Dave Gordon
Dave Gordon

Reputation: 1835

Chrome Extension: Remove body attributes from content script

This is not a duplicate... it is a continuation

I am having a problem with removing attributes from the body tag from within a Chrome Extension. I have read quite a lot about this but I am still having problems.

Take the following body element:

<body onbeforeunload="bye()" leftmargin="0" topmargin="0">

I want to remove the onbeforeunload event completely. I can inject my script into the page but it still fails to remove the event; although it does run. So the problem is purely with the injected script removing the event.

This is the injected script.

document.write('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>');
console.log("onload called");
document.removeEventListener(onload);
document.removeEventListener(onmouseover);
document.removeEventListener(onbeforeunload);
var r = document.getElementById("body");
if (r !== null)
    console.log("Found Body");
$('body').onload.off();
$('body').onbeforeunload.off();
  1. The document.write fails.
  2. the console.log works.
  3. The rest of the code fails.
  4. $ is undefined.

Any assistance to get that attribute removed would be appreciated.

Upvotes: 1

Views: 500

Answers (1)

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19080

You're mixing the JavaScript context from content script and from the web page: they are different, but share the same DOM.
That's why the $ is undefined, because it is inserted into web page, but it is used in content script.
What about just removing the attribute from body tag?

document.body.removeAttribute('onbeforeunload');

Upvotes: 1

Related Questions