我正在使用下一个代码来注入侧边栏。 https://github.com/curtislacy/inject-sidebar
function handleRequest(
//The object data with the request params
request,
//These last two ones isn't important for this example, if you want know more about it visit: http://code.google.com/chrome/extensions/messaging.html
sender, sendResponse
) {
if (request.callFunction == "toggleSidebar")
toggleSidebar();
}
chrome.extension.onRequest.addListener(handleRequest);
/*Small function wich create a sidebar(just to illustrate my point)*/
var sidebarOpen = false;
function toggleSidebar() {
if(sidebarOpen) {
var el = document.getElementById('mySidebar');
el.parentNode.removeChild(el);
sidebarOpen = false;
}
else {
var sidebar = document.createElement('div');
sidebar.id = "mySidebar";
sidebar.innerHTML = "\
<h1>Hello</h1>\
World!\
";
sidebar.style.cssText = "\
position:fixed;\
top:0px;\
left:0px;\
width:30%;\
height:100%;\
background:white;\
box-shadow:inset 0 0 1em black;\
z-index:999999;\
";
document.body.appendChild(sidebar);
sidebarOpen = true;
}
}
如何在侧边栏中加载远程URL而不是使用innerHTML? (非常新的javascript) 感谢
答案 0 :(得分:3)
要加载远程网址,您必须使用iframe
。但请记住,远程网页必须允许(许多网页不允许)。
这是一个示例扩展,它有一个brwoser-action,用于切换活动标签中的侧边栏。
侧边栏显示http://www.cnn.com/
。
在manifest.json中:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["./bg/background.js"]
},
"content_scripts": [{
"matches": ["*://*/*"],
"js": ["./fg/content.js"],
"run_at": "document_idle",
"all_frames": false
}],
"browser_action": {
"default_title": "Test Extension"
//"default_icon": {
// "19": "img/icon19.png",
// "38": "img/icon38.png"
//}
}
}
在background.js中:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.sendMessage(tab.id, { action: "toggleSidebar" });
});
在content.js中:
var sidebarURL = "http://www.cnn.com/";
var isSidebarOpen = false;
var sidebar = createSidebar();
/* Create a sidebar */
function createSidebar() {
var sb = document.createElement("iframe");
sb.id = "mySidebar";
sb.src = sidebarURL;
sb.style.cssText = ""
+ "border: 3px groove;\n"
+ "width: 30%;\n"
+ "height: 100%;\n"
+ "position: fixed;\n"
+ "top: 0px;\n"
+ "left: 0px;\n"
+ "z-index: 9999;\n"
+ "";
return sb;
}
/* Show/Hide the SideBar */
function toggleSidebar() {
if (isSidebarOpen) {
document.body.removeChild(sidebar);
} else {
document.body.appendChild(sidebar);
}
isSidebarOpen = !isSidebarOpen;
}
/* Listen for message from the background-page and toggle the SideBar */
chrome.runtime.onMessage.addListener(function(msg) {
if (msg.action && (msg.action == "toggleSidebar")) {
toggleSidebar();
}
});