My goal is to build a simple and extremely lightweight webextension, which doesn't have a background.js or content scripts, so that nothing is loaded until the user clicks the extension's toolbar button.
I know it's possible to inject javascript into a webpage without using a content script, as the Display #Anchors extension demonstrates with this snippet in its background.js file:
chrome.tabs.executeScript(tabId, {
file: 'toggle-anchors.js',
allFrames: true
});
I would like to perform this injection from popup.js, not from background.js.
However, I'm having difficulty making popup.js execute immediately when the toolbar is clicked and the popup appears. My code so far is very simple, as I'm trying to test the concept before adding more: manifest.json
{
"manifest_version": 2,
"name": "TestScript",
"version": "1.0",
"description": "testscript",
"icons": {
"48": "icon.png"
},
"permissions": [
"activeTab"
],
"browser_action": {
"default_icon": "icon-32.png",
"default_title": "Test",
"default_popup": "popup/popup.html"
},
}
popup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="choose_beast.css"/>
</head>
<body>
<script src="popup.js"></script>
</body>
</html>
popup.js
alert("Hello world!"); //I've tried various things here that would be obvious when executed, but nothing works
window.close()
I can't tell whether there's something inherent to the permissions/limitations of webextensions that is preventing the code in popup.js from running when the popup appears. Many of the examples I've looked at execute javascript triggered by an eventlistener (e.g. "Beastify," which Mozilla includes in their how-to tutorial for building webextensions):
document.addEventListener("click", (e) => {
if (e.target.classList.contains("beast")) {
var chosenBeast = e.target.textContent;
var chosenBeastURL = beastNameToURL(chosenBeast);
browser.tabs.executeScript(null, {
file: "/content_scripts/beastify.js"
});
In this case, the javascript injection is triggered by a user interaction with the popup, but is there a specific reason why the executeScript method couldn't fire immediately when the popup is opened?
(This question is a little similar to Webextension popup script not executing, but whereas that question is ultimately concerned with discovering where extensions output console logs, my question is asking specifically about how to make the popup run my code immediately. ...Also, if anyone has any thoughts about potential performance gains keeping the JS within popup.js instead of background.js/content scripts. I have enough extensions installed that it makes a noticeable dent in my browser's startup time, so I'm trying to see if I can prevent code from being loaded until it's actually fired by the browser button being clicked.)