简体   繁体   中英

With a chrome extension how can add html to just below the body tag of a page?

I want to have a chrome extension that adds a little bar to the top of certain sites. A bar similar to the one you have at the top of this site if you are logged in.

From what I have read I need to do this with a content script and I have tried various things. At present I have a file called content.js which has the following

var iframe = document.createElement("iframe");    
iframe.src = chrome.extension.getURL("iframe.html");
document.body.appendChild(iframe);

The iframe.html file is just this

<button id="button">Click me!</button>
<script>
document.getElementById("button").addEventListener("click", function() {
top.postMessage("clicked!", "*");
}, false);
</script>

This inserts this code at the bottom of the page and my problem is I would like to get it at the top. How can I do this?

您可以使用insertBeforefirstchild将其添加到顶部, firstchild所示:

document.body.insertBefore(iframe, document.body.firstChild);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM