How to insert iframe/div to the top of browser body in javascript in chrome extension

拜拜、爱过 提交于 2020-01-14 05:44:09

问题


I am new to chrome extension and did not know how to develop toolbar button in javascript/content script and want to fix it to the top of body(want to push body down). please help.

document.body.parent.style.webkitTransform ='translateY(40px)';

var div = document.createElement("div");

div.id="divs";
div.style.display='block';
div.style.width = "600px";
div.style.height = "100px";
div.style.background = "#C2E2FF";


div.style.color = "grey";


div.innerHTML = "my div";

div.appendChild(btn1);
   document.body.insertBefore(div, document.body.firstChild);
 document.getElementById("divs").style.fontStyle = 'italic';
 document.getElementById("divs").style.position = "fixed";

回答1:


You can achieve what you want by means of a content script (see example below).

If you want to inject the toolbar to specific pages only, modify the match pattern appropriately. E.g.:

// To inject toolbar only to pages like `http://*.google.com/*`
// ...replace:
matches: ["*://*/*"]

// ...with:
matches: ["http://*.google.com/*"]

Below is the source code of a demo extension that injects a toolbar in every page that has a scheme of http or https.

content.js:

var toolbarHeight = 50;

var div = document.createElement("div");
div.id = "myToolbar";
div.textContent = "I am the toolbar !";

var st = div.style;
st.display = "block";
st.top = "0px";
st.left = "0px";
st.width = "100%";
st.height = toolbarHeight + "px";
st.background = "#C2E2FF";
st.color = "grey";
st.fontStyle = "italic";
st.position = "fixed";

document.body.style.webkitTransform = "translateY(" + toolbarHeight + "px)";
document.documentElement.appendChild(div);

manifest.json:

{
    "manifest_version": 2,
    "name":    "Test Extension",
    "version": "0.0",
    "offline_enabled": true,

    "content_scripts": [{
        "matches":    ["*://*/*"],
        "js":         ["content.js"],
        "run_at":     "document_end",
        "all_frames": false
    }]
}

See, also, this excellent answer for an in-depth coverage of the subject.



来源:https://stackoverflow.com/questions/20093066/how-to-insert-iframe-div-to-the-top-of-browser-body-in-javascript-in-chrome-exte

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