单击扩展按钮后,我会在网页顶部显示一个菜单。我希望菜单保持在页面重新加载和导航域时 - 这可能吗?
mainifest.json
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [
{
"matches": ["http://*/*"],
"css": ["grid.css"],
"js": ["jquery-2.0.0.min.js"],
"all_frames": true
}
],
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, { file: "grid.js" });
});
grid.js
$(document).ready(function() {
$("body").append("<ul id='menu'><li><a id='add' href='#'>Add div</a></li></ul>")
});
答案 0 :(得分:0)
我会尝试使用LocalStorage
在您点击扩展程序的浏览器操作的同一时间保存信息。
然后在您的content_script中,您可以在LocalStorage中检查该信息并显示菜单,而无需按下扩展按钮。
简而言之,我的意思是:
<强> manifest.js 强>
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [
{
"matches": ["http://*/*"],
"css": ["grid.css"],
"js": ["jquery-2.0.0.min.js", "content.js"],
"all_frames": true
}
],
<强> background.js 强>
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, { file: "grid.js" });
chrome.tabs.sendMessage(tab.id, {menu:'show'}, function(response) {
console.log('Persistent menu started');
});
});
<强> content.js 强>
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.menu === "show")
{
localStorage.setItem("show_menu", "Yes");
}
});
var showMenu = localStorage.getItem("show_menu");
if(showMenu === "Yes")
{
$(document).ready(function() {
$("body").append("<ul id='menu'><li><a id='add' href='#'>Add div</a></li></ul>")
});
}
答案 1 :(得分:0)
MythThrazz的解决方案会导致以下行为:
如果是这样,可以使用url作为键,而不是使用“show_menu”作为键。这将允许用户按网址启动持久性菜单。
答案 2 :(得分:0)
的manifest.json:
{
"name": "permenu",
"version": "1.0",
"manifest_version": 2,
"browser_action": {
"default_icon": {
"19": "19icon.png"
},
"default_title": "permenu"
},
"background": {
"scripts": ["extension.js", "jquery-2.0.0.js"],
"persistent": true
},
"permissions": [
"tabs"
],
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["browser.js", "jquery-2.0.0.js"],
"all_frames": true
}
]
}
extension.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, {command: "add" }, function(response) {
console.log(response.toString());
});
});
});
browser.js:
chrome.runtime.onMessage.addListener(function(msg) {
if (msg.command == "add") {
doAdd("click");
}
});
document.onreadystatechange = function() {
if(document.readyState == "complete") {
doAdd("onreadystatechange");
}
};
function doAdd(reason) {
if(reason == "click") {
if(document.getElementById("add") == null) {
localStorage[location.href] = "ready";
$("body")
.append("<ul id='menu'><li><a id='add' href='#'>Add div</a></li></ul>");
}
} else if(reason == "onreadystatechange") {
if(localStorage[location.href] == "ready") {
if(document.getElementById("add") == null) {
$("body")
.append(
"<ul id='menu'><li><a id='add' href='#'>Add div</a></li></ul>");
}
}
}
}