我正在尝试使用Chrome扩展程序将div插入网页。这是我的background.js中的代码:
function CreateDiv(){
console.log("Created");
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.innerHTML = "Hello";
document.body.appendChild(div);
}
chrome.contextMenus.create({"title": "Menu", "onclick": CreateDiv});
console.log("Loaded");
经过大约一个小时的试验,我发布了它要在background.html页面上创建div的功能,当时我希望它在我当前正在查看的页面上创建div的功能。有人知道我该怎么做吗?我已经看到它通过诸如“广告块”之类的扩展来完成,并且看过代码,但仍然迷失了方向……有人对我如何做到这一点有任何建议吗?
更改活动标签的HTML所需要做的就是将信息发送到content.js并在其中创建。要从background.js发送信息,您可以像这样使用chrome.tabs.sendMessage
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {createDiv: {width: "100px", height: "100px", innerHTML: "Hello"}}, function(response) {
console.log(response.confirmation);
});
});
并在content.js中获取该信息,请执行以下操作
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.requested == "createDiv"){
//Code to create the div
sendResponse({confirmation: "Successfully created div"});
}
});
请记住在清单文件中列出您的内容脚本。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句