Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
85
rated 0 times [  88] [ 3]  / answers: 1 / hits: 14635  / 11 Years ago, sat, february 8, 2014, 12:00:00

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?


More From » html

 Answers
23

What 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.


[#47934] Friday, February 7, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackelyn

Total Points: 303
Total Questions: 103
Total Answers: 102

Location: Turks and Caicos Islands
Member since Sun, Mar 7, 2021
3 Years ago
jackelyn questions
Thu, Apr 8, 21, 00:00, 3 Years ago
Sun, Feb 28, 21, 00:00, 3 Years ago
Mon, May 25, 20, 00:00, 4 Years ago
Thu, Apr 30, 20, 00:00, 4 Years ago
;