Javascript 将消息发送到后台页面,更新html,然后在选项卡中显示
我有一个chrome扩展,用户在其中输入一些信息并生成报告。当然,根据用户输入的内容,该报告每次都会有所不同 我想要实现的是,我的扩展要说: 嘿,背景页先生。这是您需要的信息,现在根据我给您的内容构建一些html,并将其显示给用户 下面是我正在使用的Javascript 将消息发送到后台页面,更新html,然后在选项卡中显示,javascript,html,google-chrome-extension,Javascript,Html,Google Chrome Extension,我有一个chrome扩展,用户在其中输入一些信息并生成报告。当然,根据用户输入的内容,该报告每次都会有所不同 我想要实现的是,我的扩展要说: 嘿,背景页先生。这是您需要的信息,现在根据我给您的内容构建一些html,并将其显示给用户 下面是我正在使用的manifest.json: { "manifest_version": 2, "name": "XXXX", "description": "XXXX", "version": "1.0.0", "permissions":
manifest.json
:
{
"manifest_version": 2,
"name": "XXXX",
"description": "XXXX",
"version": "1.0.0",
"permissions": ["storage", "tabs"],
"options_page": "settings.html",
"background":
{
"page": "background.html"
},
"content_scripts":
[
{
"matches": ["<all_urls>"],
"js": ["js/jquery-3.1.1.min.js", "js/bootstrap.min.js", "js/main.js", "js/background.js"],
"css": ["css/bootstrap.min.css", "css/font-awesome.min.css"]
}
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"icons": { "128": "logo.png" }
}
这是我的background.js
$(document).ready(function() {
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
$("body").html(msg.message);
console.log("Message from: " + msg.message);
});
});
现在,当用户单击我的分机上的按钮时,我使用以下代码发送消息:
$("#generate").click(function() {
chrome.tabs.create({url: 'background.html'});
chrome.runtime.sendMessage({
message: "Sample message."
});
});
现在我所期望的是打开我的background.html
页面,然后根据发送的消息更改页面主体,但这不起作用
有什么想法吗?你试图用同一页作为背景并显示一些东西,这是一个巨大的概念错误。这可能导致非常不可预测的行为 实际上,您正试图打开一个带有
background.html
的选项卡,并以某种方式期望它是“相同”的背景页面。它不是那样工作的-您正在打开同一文档的新实例。考虑一下在两个选项卡中打开同一个web表单——您不希望它们将输入的文本镜像到字段中
最重要的是,在弹出页面与打开标签的交互方面,有很多错误堆积在一起
因此,行动计划:
background.js
,然后切换到scripts
-样式的背景页面定义:
"background": {
"scripts": ["background.js"]
}
也可考虑使用< < /P>
background
。将其重命名为report.html
/report.js
选项卡的回调。如果要确保页面实际打开并准备就绪,请创建
chrome.tabs.create({url: "report.html"}, function(tab) {
// Okay, now it's ready, right? Right?..
chrome.runtime.sendMessage(/*...*/);
});
// Popup
chrome.storage.local.set({foo: bar}, function() {
// Storage is updated, it's showtime!
chrome.tabs.create({url: "report.html"});
// And now, we die, inevitably. Goodbye, cruel world.
});
// Report
chrome.storage.local.get("foo", function(data) {
// Oh, what joy is to have data.foo in here!
});
实际上,
background.js
最初被称为test.js
,为了这个线程,我忘了重命名它。不管怎样,谢谢你提供的信息!另外,chrome.storage.local
,这是否意味着这些数据会在以后被销毁而不像chrome.storage.sync
?不,这意味着它会留在您的计算机上,而不是试图通过登录的谷歌帐户进行复制。我明白了。非常感谢。
// Popup
chrome.storage.local.set({foo: bar}, function() {
// Storage is updated, it's showtime!
chrome.tabs.create({url: "report.html"});
// And now, we die, inevitably. Goodbye, cruel world.
});
// Report
chrome.storage.local.get("foo", function(data) {
// Oh, what joy is to have data.foo in here!
});