问题
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?
回答1:
You can add it to the top by using insertBefore
and firstchild
like so:
document.body.insertBefore(iframe, document.body.firstChild);
来源:https://stackoverflow.com/questions/8986752/with-a-chrome-extension-how-can-add-html-to-just-below-the-body-tag-of-a-page