我有一个chrome扩展程序,用户输入一些信息并生成报告。当然,根据用户输入的内容,此报告每次都会有所不同。
我希望实现的目标是:我的扩展名是:
嘿,背景先生页面。这是您需要的信息,现在根据我给您的内容构建一些HTML并将其显示给用户。
以下是我正在使用的{
"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.html
这是我的<html>
<body>
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/background.js"></script>
</body>
</html>
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
现在我期望发生的事情是,我的msgattrib.exe
msgcat.exe
msgcmp.exe
msgcomm.exe
msgconv.exe
msgen.exe
msgexec.exe
msgfilter.exe
msgfmt.exe
msggrep.exe
msginit.exe
msgmerge.exe
msgunfmt.exe
msguniq.exe
xgettext.exe
页面打开,然后根据发送的消息更改页面正文,但这不起作用。
有什么想法吗?
答案 0 :(得分:1)
您通过尝试将相同的页面用于背景并显示某些内容来制作巨大的概念错误。这可能导致非常不可预测的行为。
您实际上是在尝试使用background.html
打开一个标签,并以某种方式期望它是“相同”的背景页面。它不会那样 - 您正在打开同一文档的新实例。想想在两个选项卡中打开相同的Web表单 - 您不希望它们镜像输入到字段中的文本。
最重要的是,弹出页面与开放标签的互动会产生很多错误。
所以,行动计划:
如果您真的需要在(永久不可见的)背景页面中执行一段代码,请以惯用方式background.js
调用它并切换到scripts
- 样式背景页面定义:
"background": {
"scripts": ["background.js"]
}
另外,请考虑使用Event pages。
无论您使用哪种报告显示都应该不为了您的理智而被称为background
。将其重命名为report.html
/ report.js
。
在你的弹出代码中,你的错误#1是时间。你打开一个应该听你的消息的页面,但不要等它准备好听。如果要确保页面实际打开并准备就绪,则应使用tabs.create
的回调。
chrome.tabs.create({url: "report.html"}, function(tab) {
// Okay, now it's ready, right? Right?..
chrome.runtime.sendMessage(/*...*/);
});
然而,这样做将不会解决问题,因为默认情况下打开一个新标签会将其关注(大概是你想要的东西),这会立即强制关闭弹出窗口。一旦选项卡聚焦,您就无法阻止它。但这意味着你的消息不会被发送:弹出窗口会在它发生之前被销毁。
所以,不要依赖消息传递。据推测,您可以store您的报告基于存储的任何数据。因此,首先设置 ,然后打开报告页面,您可以在其中读取数据并构建报告。
// 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!
});