I have a site which have this element :
<input type="text" id="editpane_title" fnk="tt" maxlength="80" name="title" value="st benedict crucifix">
And I want to get and set value of that input using Chrome Extension :
{
"manifest_version": 2,
"name": "demo",
"version": "1.0",
"description": "demo",
"icons": { "16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png" },
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": [ "tabs" ],
"browser_action": {
"default_icon": {
"16": "icon16.png",
"24": "icon24.png",
"32": "icon32.png"
},
"default_title": "demo"
}
}
and here's background.js
:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
var title = document.getElementById('editpane_title').value;
alert(title);
});
});
and the alert is not showing up at all. I tried reload multiple times but still failed.
what did I missed here?
Two issues here.
First off, code not working and you have no idea why.
alert is not showing up at all
You need to learn to debug extensions to understand what's wrong. Trying to solve the problem yourself is important even if you fail to do so. There's Google's own somewhat dated tutorial that mostly covers popups, and there's this canonical question for background scripts:
Where to read console messages from background.js in a Chrome extension?
So suppose you follow the advice and try debugging. You will quickly learn that alert
is not called, because there's an exception:
Uncaught TypeError: Cannot read property 'value' of null
That leads to a second problem: document.getElementById('editpane_title')
can't find the element.
Ask yourself: which document
is referenced here? Or rather, why would it automagically be the page you're looking at?
At this point, you should read the Architecture Overview. You'll learn there:
document
, you need a Content Script.storage
API.Armed with that knowledge, you should now turn to the following canonical question:
How to access the webpage DOM rather than the extension page DOM?
As a final point, you should not be using alert
to inspect the state of your program, or for any reason really.
This ancient mechanism is blocking: it stops JS context from doing anything until you dismiss the modal window. This screws up with some extension APIs that are asynchronous and interface with native components of the browser.
In fact, in Firefox WebExtensions you expicitly can't use them from a background page.
So, wean off this bad habit early:
printf
/echo
-style debugging is console.log()
, with the output accessible as explained in the debugging section.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With