【发布时间】:2018-04-30 00:08:28
【问题描述】:
我有一个 chrome 扩展程序,我会定期根据某些内容发出警报。
问题是 Javascript 中的默认警报非常丑陋,我正在尝试用更漂亮的东西替换它。
问题是当前警报是从后台脚本触发的。 Google 不允许我们在后台 html 中包含任何外部库。
鉴于这个问题,我该如何用更现代的 UI 警报替换默认警报?
我希望将默认警报替换为 SweetAlert 之类的内容。
我的 background.js 目前看起来像这样:
// on some alarm trigger
function showpopup() {
console.log(" in show popuup");
console.log(Date());
alert("ugly alert");
}
我还探索了从我的后台文件中注入另一个 js 文件的选项。
function showpopup() {
console.log(" in show popuup");
console.log(Date());
var s = document.createElement('script');
// added "script.js" to web_accessible_resources in manifest.json
s.src = chrome.extension.getURL('script.js');
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
}
我的 script.js 目前只是调用警报
alert("ugly alert now in script.js");
我无法弄清楚如何在这个 javascript 文件 script.js 中创建我自己的对话框。
【问题讨论】:
-
您不能以这种方式将代码注入活动页面,但是您不需要 - 签出 chrome.tabs.executeScript。基本上,您需要使用后台脚本中的该命令或通过在清单“content_scripts”部分中指定来将脚本注入页面。然后在那个脚本中你需要一个消息监听器 chrome.runtime.onMessage.addListener。然后,您将在后台脚本中使用 chrome.runtime.sendMessage 来调用活动选项卡中的脚本。这应该足以提供帮助。
标签: google-chrome-extension google-chrome-devtools google-chrome-app