最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论