简体   繁体   中英

I can't access the web page DOM from a Chrome Extension pop up

I am struggling to access the DOM of the web page for my Chrome Extension.

In one extension I made, my extension parses the DOM from the content.js file without issue. This happens as the page loads. The user does not need to interact/open the extension at all, it just needs to be running in the backgorund.

Now I'm trying to trigger this from a button. This means the user will click the extension icon in the browser, and the popup.html will show some HTML (including the button).

This is where the problem lies for me. When I now try access the DOM (via click event of the button), it shows the popup.html's DOM, not the web page (The active tab).

So, a quick look through the docs (which I'm open to admit I struggle with) show that it could be a permissions issue. In my manifest.json file, I added

"permissions": [
"activeTab"
],

This didn't help:(

So in this new extension, I'm not using the background.js nor content.js.. I guess this is the problem, as the javascript I'm calling is embeded in the HTML pop up. This makes sense to me (as to the behaviour I'm getting).

How do I access the DOM of the active tab from the HTML pop up

The only way of accessing a page's DOM is by using a content script. Since you've set the activeTab permission you can use chrome.tabs.executeScript to inject a content script into the active tab by omitting the first parameter (the tabId ).

Here is an example:

chrome.tabs.executeScript({ file: "content.js" });

I have had this same issue, I click on the button to open an popup, then how do I access the contents of the popup. Yes, you will need to use content scripts, but a trick I done to accomplish this, was when the popup is open, use window.name and get the name of that window. Then you can reference that popup window by var test = window.name('', 'name of that window'). Then you can reference the dom elements of the popup from test. Worked for me, let me know if I need to include some code to better explain.

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