Improve content script injection

This commit is contained in:
Will Bamberg
2017-07-06 19:31:10 -07:00
parent 5916a3de93
commit 273c3c5690
2 changed files with 33 additions and 12 deletions

View File

@@ -2,12 +2,10 @@
beastify():
* removes every node in the document.body,
* then inserts the chosen beast
* then removes itself as a listener
*/
function beastify(request, sender, sendResponse) {
removeEverything();
insertBeast(request.beastURL);
browser.runtime.onMessage.removeListener(beastify);
}
/*

View File

@@ -16,33 +16,56 @@ function beastNameToURL(beastName) {
Listen for clicks in the popup.
If the click is on one of the beasts:
Inject the "beastify.js" content script in the active tab.
(1) inject the test script into the active tab.
This checks whether the tab's scope includes a function called "beastify()".
Then get the active tab and send "beastify.js" a message
containing the URL to the chosen beast's image.
(2) if the tab doesn't already have a function called "beastify()",
then inject the beastify.js content script. Otherwise, do nothing.
This should ensure that beastify.js is only injected once, even if
the user clicks a beast again.
(3) send a message to "beastify.js" that contains the URL to
the chosen beast's image.
If it's on a button wich contains class "clear":
Reload the page.
Close the popup. This is needed, as the content script malfunctions after page reloads.
*/
document.addEventListener("click", (e) => {
if (e.target.classList.contains("beast")) {
function injectTestScript() {
return browser.tabs.executeScript({
code: "typeof beastify === 'function';",
});
}
function injectBeastify(testResults) {
if (!testResults || testResults[0] !== true) {
return browser.tabs.executeScript({
file: "/content_scripts/beastify.js"
});
} else {
return Promise.resolve(true);
}
}
function messageBeastify() {
var chosenBeast = e.target.textContent;
var chosenBeastURL = beastNameToURL(chosenBeast);
browser.tabs.executeScript(null, {
file: "/content_scripts/beastify.js"
});
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then((tabs) => {
browser.tabs.sendMessage(tabs[0].id, {beastURL: chosenBeastURL});
});
}
if (e.target.classList.contains("beast")) {
injectTestScript()
.then(injectBeastify)
.then(messageBeastify);
}
else if (e.target.classList.contains("clear")) {
browser.tabs.reload();
window.close();
return;
}
});