我想了解有关Chrome扩展的知识,但我无法理解如何使用content_scripts
操纵页面的DOM
。在Chrome扩展中操纵DOM
的manifest.json
{
"name": "First",
"version": "1.0",
"manifest_version": 2,
"description": "First extension",
"background": {
"scripts": ["test.js"]
},
"page_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [ {
"js": [ "jquery.min.js", "popup1.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ],
"permissions" : [
"tabs",
"http://*/*"
]
}
test.js
function check(tab_id, data, tab){
if(tab.url.indexOf("google") > -1){
chrome.pageAction.show(tab_id);
}
};
chrome.tabs.onUpdated.addListener(check);
popup1.js
function myfunc(){
var x = $('#options option:selected').text();
$("body").append('Test');
alert(x);
//window.close();
}
$(document).ready(function(){
$('#options').change(myfunc);
});
上面的代码/扩展工作正常,因为myfunc
被调用,但它不会将Test
注入到google.com
的主体中。
所以,我在哪里访问/操作DOM错误。
首先,你不需要绑定到'ready',因为你的内容脚本在'document_idle'处执行(默认),这保证在DOM准备就绪后发生。其次,请提供更多关于你在'myfunc'中看到的信息:或者你在控制台中可能存在一些错误,或者你确实忽视了正文中添加的文本。我不确定,是不是'$(“body”)。append(document.createTextNode(“Test”));'? – Stan
顺便说一句,如果您在追加后关闭窗口,您如何检查身体? – Stan
另外我想确保你不会将'popup1.js'加载到popup.html中,并尝试使用'popup1.js'作为网页的一部分并在弹出窗口中完成一些技巧时间。你有什么要求?为什么你将内容脚本命名为“弹出”? – Stan