通过chrome扩展访问DOM元素

The*_*One 13 javascript dom google-chrome-extension

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

<html>
  <button id="mybutton">click me</button>
</html>
Run Code Online (Sandbox Code Playgroud)

我想通过chrome扩展访问innerHTML("click me"):

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

当我点击扩展名时,弹出窗口显示:"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
}
Run Code Online (Sandbox Code Playgroud)

The*_*One 32

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

的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"]
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

的index.html

<html>
  <button id="mybutton">click me</button>
</html>
Run Code Online (Sandbox Code Playgroud)

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