Reputation: 1011
I am migrating my old Firefox extenstion to WebExtenstion API. Here is what my extension does:
So here is my manifest.json:
{
"manifest_version": 2,
"name": "Login",
"version": "3.0",
"description": "Login to myinterfaces",
"homepage_url": "localhost",
"icons": {
"48": "icons/button-1.png"
},
"permissions": [
"activeTab", "storage", "tabs"
],
"browser_action": {
"default_icon": "icons/button-1.png",
"default_title": "My Login"
},
"options_ui": {
"page": "options.html"
},
"background": {
"scripts": ["index.js"]
}
}
In index.js, I successfully get the values from the option page and determine the URL of my active tab. After that, I am trying to modify the values on the page. Here is how I do it:
var doc = window.content.document;
doc.getElementById("btnLogin").disabled = false;
doc.getElementById("loginUserName").value = loginUserName;
doc.getElementById("loginPassword").value = loginPassword;
But for ...
doc.getElementById("btnLogin").disabled = false;
... I am getting:
TypeError: doc.getElementById(...) is null
So I read this page: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Modify_a_web_page
Not sure if I understand everything correctly, so here are some questions:
Is it possible to access the web page from the background script? If it is possible, how to cope with the error I have? If it is not possible, do I understand right that I am supposed to use messaging between content and background scripts? So do I have to send loginUserName and loginPassword values from the background script to the content script and modify the page in the content script? Is it correct?
Thanks, Racoon
Upvotes: 0
Views: 1501
Reputation: 77541
Is it possible to access the web page from the background script?
No. window.content.document
is the background page in that context. Think of a background page as a separate document open in an invisible tab.
You need a content script and need to communicate with it. See Chrome documentation on extension architecture - I'm sure there are similar on MDN.
If it is not possible, do I understand right that I am supposed to use messaging between content and background scripts? So do I have to send loginUserName and loginPassword values from the background script to the content script and modify the page in the content script?
This is correct, though if you use browser.storage
for options you can directly access that from a content script.
But you will need messaging: only the background page can get the onClicked
event for your toolbar button ("browser action" in WebExtension terms).
Note that you don't have to inject the content script in advance (through manifest). You can use programmatic injection + "activeTab"
permission here, which results in better performance for the user when not using your extensions and far less scary permission warnings.
Upvotes: 1