The*_*One 2 html javascript google-chrome-extension
我有一个 chrome 扩展,用户输入一些信息并生成报告。当然,现在该报告每次都会根据用户输入的内容而有所不同。
我想要实现的目标是让我的扩展说:
嘿,背景页先生。这是您需要的信息,现在根据我给您的信息构建一些 html 并将其显示给用户。
这是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" }
}
Run Code Online (Sandbox Code Playgroud)
这是我的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>
Run Code Online (Sandbox Code Playgroud)
这是我的background.js
$(document).ready(function() {
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
$("body").html(msg.message);
console.log("Message from: " + msg.message);
});
});
Run Code Online (Sandbox Code Playgroud)
现在,当用户单击我的扩展上的按钮时,我使用以下代码发送消息:
$("#generate").click(function() {
chrome.tabs.create({url: 'background.html'});
chrome.runtime.sendMessage({
message: "Sample message."
});
});
Run Code Online (Sandbox Code Playgroud)
现在我期望发生的事情是background.html
打开我的页面,然后根据发送的消息更改页面正文,但这不起作用。
有任何想法吗?
通过尝试使用同一页面作为背景并显示某些内容,您犯了一个巨大的概念错误。这可能会导致非常不可预测的行为。
您本质上是在尝试打开一个选项卡background.html
,并以某种方式期望它是“相同的”背景页面。它不是这样工作的 - 你正在打开一个新实例同一文档的想象一下在两个选项卡中打开相同的 Web 表单 - 您不希望它们反映输入到字段中的文本。
最重要的是,弹出页面与打开选项卡的交互存在很多错误。
因此,行动计划:
如果您确实需要在(永久不可见)后台页面中执行一段代码,请按惯用方式调用它background.js
并切换到scripts
-style 后台页面定义:
"background": {
"scripts": ["background.js"]
}
Run Code Online (Sandbox Code Playgroud)
另外,请考虑使用事件页面。
为了您的理智,无论您使用什么来显示报告,都不应该调用它。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(/*...*/);
});
Run Code Online (Sandbox Code Playgroud)然而,这样做并不能解决问题,因为默认情况下打开一个新选项卡会聚焦它(这可能是您想要的),这会立即强制弹出窗口关闭。一旦选项卡获得焦点,您就无法阻止它。但这意味着您的消息不会被发送:弹出窗口将在其发生之前被销毁。
因此,不要依赖消息传递。据推测,您可以将报告所基于的任何数据存储在存储中。因此,首先设置它,然后打开报告页面,您可以在其中读取数据并构建报告。
// 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!
});
Run Code Online (Sandbox Code Playgroud) 归档时间: |
|
查看次数: |
1130 次 |
最近记录: |