javascript - Chrome extension, how to create overlay over webpage? - Stack Overflow

I'm trying to insert a div into a webpage using a Chrome extension. Here's my code in my back

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 badges
Add a comment  | 

1 Answer 1

Reset to default 13

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1739451169a4127866.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信