通过chrome扩展访问DOM元素

时间:2014-01-23 17:10:37

标签: javascript dom google-chrome-extension

我正在尝试从网页访问一些DOM元素:

<html>
  <button id="mybutton">click me</button>
</html>

我想通过chrome扩展程序访问innerHTML(“click me”):

chrome.browserAction.onClicked.addListener(function(tab) {
    var button = document.getElementById("mybutton");
    if(button == null){
        alert("null!");
    }
    else{
        alert("found!");
    }
});

当我点击扩展名时,弹出窗口显示:“null”。 我的manifest.json:

{
    "name": "HackExtension",
    "description": "Hack all the things",
    "version": "2.0",
    "permissions": [
    "tabs", "http://*/*"
    ],
    "background": {
    "scripts": ["contentscript.js"],
    "persistent": false
    },
    "browser_action": {
    "scripts": ["contentscript.js"],
    "persistent": false
    },
    "manifest_version": 2
}

1 个答案:

答案 0 :(得分:31)

解决方案: 您需要清单文件,后台脚本和内容脚本。在您必须使用它的文档中以及如何使用它并不是很清楚。要提醒完整的dom,请参阅here。因为我很难找到一个真正有效的完整解决方案,而不仅仅是像我这样对新手没用的片段,我提供了一个特定的解决方案:

<强>的manifest.json

{
    "manifest_version": 2,
    "name":    "Test Extension",
    "version": "0.0",

    "background": {
        "persistent": false,
        "scripts": ["background.js"]
    },
    "content_scripts": [{
        "matches": ["file:///*"],
        "js":      ["content.js"]
    }],
    "browser_action": {
        "default_title": "Test Extension"
    },

    "permissions": ["activeTab"]
}

<强> content.js

/* Listen for messages */
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
    /* If the received message has the expected format... */
    if (msg.text && (msg.text == "report_back")) {
        /* Call the specified callback, passing 
           the web-pages DOM content as argument */
    sendResponse(document.getElementById("mybutton").innerHTML);
    }
});

<强> background.js

/* Regex-pattern to check URLs against. 
   It matches URLs like: http[s]://[...]stackoverflow.com[...] */
var urlRegex = /^file:\/\/\/:?/;

/* A function creator for callbacks */
function doStuffWithDOM(element) {
    alert("I received the following DOM content:\n" + element);
}

/* When the browser-action button is clicked... */
chrome.browserAction.onClicked.addListener(function(tab) {
    /*...check the URL of the active tab against our pattern and... */
    if (urlRegex.test(tab.url)) {
        /* ...if it matches, send a message specifying a callback too */
        chrome.tabs.sendMessage(tab.id, { text: "report_back" },
                                doStuffWithDOM);
    }
});

<强>的index.html

<html>
  <button id="mybutton">click me</button>
</html>

只需将index.html保存在某处,然后将其作为扩展名加载到文件夹中,其中包含其他三个文件。打开index.html并按下扩展按钮。它应该显示“点击我”。