2014-01-23 181 views
11

我试图从网页访问某些DOM元素:访问DOM元素

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

我想通过一个浏览器扩展程序来访问的innerHTML(“点击我”):

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 
} 
+2

[Chrome扩展 - 获取DOM内容]的可能重复(http://stackoverflow.com/questions/19758028/chrome-extension-get-dom-content) –

回答

29

解决办法: 你需要一个清单文件,背景脚本和内容脚本。这在文档中不太清楚,您必须使用它以及如何使用它。有关警报的完整信息,请参阅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"] 
} 

内容.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并按下扩展按钮。它应该显示“点击我”。

+0

添加到此:内容脚本是脚本可以访问网页的DOM。如果需要,它可以将元素传递给另一个脚本。上面的例子使用后台脚本,但它可能是一个弹出窗口。 – Bees

+0

你介意解释''匹配“:[”file:/// *“],'line?这不仅适用于本地文件吗? –

+0

它可以工作,但只要在“browser_action”(manifest.json)中添加一个''default_popup“:”popup.html“'就会停止工作。 –