I'm trying to insert a div into a webpage using a Chrome extension. Here's my code in my 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");
After about an hour of experimenting, I released that it's creating a div on the background.html page, when I want it to create the div on the page I'm currently looking at. Has anybody got a way how I can do this? I've seen it done with extensions such as 'Ad Block' and I've looked at the code but I'm still lost... Has anybody got any suggestions on how I can do this?
I'm trying to insert a div into a webpage using a Chrome extension. Here's my code in my 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");
After about an hour of experimenting, I released that it's creating a div on the background.html page, when I want it to create the div on the page I'm currently looking at. Has anybody got a way how I can do this? I've seen it done with extensions such as 'Ad Block' and I've looked at the code but I'm still lost... Has anybody got any suggestions on how I can do this?
Share Improve this question asked Feb 8, 2014 at 14:02 XancoXanco 9021 gold badge10 silver badges15 bronze badges1 Answer
Reset to default 13What you need to do to change the HTML of the active tab is to send the info over to content.js and create it there. To send the information from background.js you can use chrome.tabs.sendMessage like so
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);
});
});
and to get that info in content.js you do the following
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.requested == "createDiv"){
//Code to create the div
sendResponse({confirmation: "Successfully created div"});
}
});
Remember to list your content script in your manifest file.