Files
webextensions-examples/beastify/content_scripts/beastify.js
wbamberg 37cb9f7a84 Improve content script injection (#240)
* Improve content script injection

* Add an error handler for content script injection

* Use a guard variable in the content script, instead

* Fix comment

* Ensure tabID is unchanged; fix image styles

* Only inject script once; use CSS to hide page

* Display an error when the script can't be executed; document other limitations

* Log error on script execute failure
2017-11-01 11:25:34 -07:00

49 lines
1.2 KiB
JavaScript

(function() {
/**
* Check and set a global guard variable.
* If this content script is injected into the same page again,
* it will do nothing next time.
*/
if (window.hasRun) {
return;
}
window.hasRun = true;
/**
* Given a URL to a beast image, remove all existing beasts, then
* create and style an IMG node pointing to
* that image, then insert the node into the document.
*/
function insertBeast(beastURL) {
removeExistingBeasts();
let beastImage = document.createElement("img");
beastImage.setAttribute("src", beastURL);
beastImage.style.height = "100vh";
beastImage.className = "beastify-image";
document.body.appendChild(beastImage);
}
/**
* Remove every beast from the page.
*/
function removeExistingBeasts() {
let existingBeasts = document.querySelectorAll(".beastify-image");
for (let beast of existingBeasts) {
beast.remove();
}
}
/**
* Listen for messages from the background script.
* Call "beastify()" or "reset()".
*/
browser.runtime.onMessage.addListener((message) => {
if (message.command === "beastify") {
insertBeast(message.beastURL);
} else if (message.command === "reset") {
removeExistingBeasts();
}
});
})();