简体   繁体   中英

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.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM