简体   繁体   中英

Google Chrome: can't getElementById from chrome extension

Eg, I'm trying to read the text of the element with id="tooltip" at https://developer.chrome.com/extensions/browserAction

The following code works fine from console:

var element = document.getElementById('tooltip');
if(element != null) {alert(element.innerText);}
else {alert("element contains null");}

Same code r u n from an extension shows "element contains null".

chrome.browserAction.onClicked.addListener
(
  function(tab)
  {
    var element = document.getElementById('tooltip');
    if(element != null) {alert(element.innerText);}
    else {alert("element contains null");}
  }
);

And it's not surprising, because the document object contains the _generated_background_page.html , and not my page in question. And the actual page I need seems to be contained in tab object. So the question now is How to search for "tooltip" in tab ?

I used the following code to see the contents of the above-mentioned objects: alert(JSON.stringify(tab, null, 4));
alert(JSON.stringify(document, null, 4));

Perhaps it is onclick not onclicked

chrome.browserAction.onClick.addListener
(
  function(tab)
  {
    var element = document.getElementById('tooltip');
    alert(element.innerText);
  }
);

I seem to have found a solution. I'm not sure if it's the most elegant one, but still it works.

I created a second script named script2.js and refer to it from script1.js .

Below is the contents of script1.js which is executed when I click the extension's button in the toolbar of the browser:

chrome.browserAction.onClicked.addListener(function(tab){
  chrome.tabs.executeScript(null, {file: "script2.js"});
});

script1.js calls script2.js which contains the main code:

var element = document.getElementById('tooltip');
if(element != null) alert(element.innerText);
else alert('element is null');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM