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

删除回忆录丶 提交于 2020-01-02 05:30:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!