每当我双击一个单词/选择它时,我都会尝试触发通知。在网上找到了几个例子,但我仍然无法让我的例子工作:
list :
{
"name": "hh",
"description": "hh!",
"manifest_version": 2,
"version": "0.0.0.1",
"content_scripts": [
{
"matches": [ "http://*/*", "https://*/*" ],
"js": [ "background.js" ],
"all_frames": true,
"run_at": "document_end"
}
],
"permissions": ["storage", "notifications"],
"icons": { "128": "neoprice.png" }
}
背景.js
var listener = function(evt) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
displayPrice();
var range = selection.getRangeAt(0);
var text = range.cloneContents().textContent;
console.log(text);
}
};
document.addEventListener('dblclick', listener);
function displayPrice(){
chrome.notifications.create(getNotificationId(), {
title: "message.data.name",
iconUrl: 'hh.png',
type: 'basic',
message: "message.data.prompt"
}, function() {});
}
// Returns a new notification ID used in the notification.
function getNotificationId() {
var id = Math.floor(Math.random() * 9007199254740992) + 1;
return id.toString();
}
我之前添加了以下内容,但我看到人们没有使用它,所以我删除了它
"app": {
"background": {
"scripts": ["background.js", "assets/jquery.min.js"]
}
},
我想要实现的目标:每当他们进入任何页面选择一个单词时,它就会触发该功能。稍后,我希望将其用于特定页面。 :)
尝试过:How to keep the eventlistener real time for chrome extensions?
Chrome extension double click on a word
https://github.com/max99x/inline-search-chrome-ext
两者都没有真正按照我想要的那样工作。 :(
最佳答案
解决方案
您似乎对 background page 感到困惑和 content script 。事实上,您的 background.js
是一个内容脚本
,尽管它的名称是“background”。而chrome.notifications api只能在后台页面
中调用,尝试注释displayPrice
函数将使您的代码正常工作。
下一步
看看上面的教程,wdblclick
事件触发器,使用Message Passing与后台页面通信并在后台页面调用chrome.notications
api。
还有什么
chrome apps中使用了以下代码而不是chrome extension .
"app": {
"background": {
"scripts": ["background.js", "assets/jquery.min.js"]
}
},
关于javascript - 双击/选择单词时在 Chrome 扩展中运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35905941/