简体   繁体   中英

Chrome extension: content script not finding dom elements

I'm writing a chrome extension and have the following code

popup.html:

   <script type='text/javascript' src='content.js'></script>

content.js:

var container = document.getElementById('viewer')
container.style['white-space'] = 'nowrap'

var node_list = document.getElementsByClassName('page')
Array.prototype.forEach.call(node_list, function(page) {
  page.style['display'] = 'inline-block'
})

manifest.json:

{
    "name": "horizontal_pdf",
    "version": "0.0.1",
    "manifest_version": 2,
    "browser_action": {
        "default_title": "My Title",
        "default_popup": "popup.html",
        "default_icon": {
            "16": "icons/16x16.jpg",
            "32": "icons/32x32.jpg"
        }
    }
}

But when I click on the icon, and look at the console, I see the error message:

Uncaught TypeError: Cannot read property 'style' of null 

at line 2 of content.js. So, it's not able to find the div with id viewer . But when I look at the page's dom, it's there. What am I doing wrong?

PS: I don't have content scripts specified in the manifest since I don't want it to get triggered automatically, but only when the user clicks on the icon.

According to Google's documentation you can use programmatic injection.

In a background script you can add:

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

Or maybe in you popup script you can call:

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

(You'll need to add the activeTab permission any way)

https://developer.chrome.com/extensions/content_scripts#pi

如果要在popup.html / js中获取dom,则必须为内容脚本添加content.js,然后将消息发送到popup.js,您可以从popup.js调用content.js以获取信息...背景脚本无法访问dom ...这是我所做的...

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