我正在尝试为Chrome创建一个新的扩展程序,它将解析当前选项卡的HTML代码并对其进行处理。
这是我到目前为止所得到的。
的manifest.json
{
"name": "some name",
"manifest_version": 2,
"version": "0.2",
"description": "does something",
"browser_action": {
"default_icon": "logo.png",
"default_popup": "popup.html"
},
"icons": {
"128": "icon_128x128.png",
"16": "icon_16x16.png",
"48": "icon_48x48.png"
},
"background": {
"scripts": ["info.js", "mainme.js"]
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
]}
info.js
function init() {
var button = document.getElementById("clickhere");
if(button.addEventListener){
button.addEventListener("click", function() {
//function here
chrome.tabs.executeScript(null,{file: "mainme.js"});
//function end
}, false);
} else if(button.attachEvent){
button.attachEvent("onclick", function() { alert("alert");});
}
};
if(window.addEventListener){
window.addEventListener("load", init, false);
} else if(window.attachEvent){
window.attachEvent("onload", init);
} else{
document.addEventListener("load", init, false);
}
mainme.js
var maintest = document.getElementsByTagName('html')[0].innerHTML;
var mtest = maintest.search("<body");
document.getElementById("divy").innerHTML=mtest;
popup.html
<HTML>
<head>
<script type="text/javascript" src="info.js"></script>
</head>
<body>
<div id="divy" width="200" height="400">blank</div>
<button id="clickhere">Press</button>
</body>
</html>
我的想法是,当我点击popup.html上的按钮时,div id =“divy”应该更改为mtest变量。我认为一切正常但问题是,当我点击按钮id =“clickhere”时,我得到“未捕获的TypeError:无法在控制台日志中设置属性'innerHTML'的null”错误。
主要是扩展到目前为止添加了监听器“onclick”并触发了指向mainme.js的chrome.tabs.executeScript函数,然后在mainme.js中它获取当前选项卡的页面源,将其分配给maintest然后它搜索
ChrisP回答后更新:
首先,我要感谢提示。
我将清单改为包含此
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["mainme.js"]
}
],
然后我对mainme.js有一些疑问我应该如何编写代码?我在想下面的事情
chrome.runtime.sendMessage({code:var maintest = document.getElementsByTagName('html')[0].innerHTML;var mtest = maintest.search("<body");}, function(response) {
window.document.getElementById("divy").innerHTML=mtest;
});
我不确定如何实现我的代码:(
答案 0 :(得分:1)
由于Chrome扩展程序只能在Chrome中运行,因此您可以保证定义方法addEventListener
,而attachEvent
则不然。所以不需要测试。
据我了解,您正在尝试从当前打开的选项卡中提取内容,并将其显示在弹出窗口中。如果没有为您编写完整的代码,以下是我的建议:
mainme.js
脚本。您可以从manifest.json
文件中执行此操作,有关详细信息,请参阅http://developer.chrome.com/extensions/content_scripts.html。背景页面是扩展的基石。基本上,您的扩展程序应如下所示:
web page <=> background page <=> popup page
答案 1 :(得分:0)
尝试替换
document.getElementById("divy").innerHTML=mtest;
与
window.document.getElementById("divy").innerHTML=mtest;