在双击/选择单词时在 chrome 扩展程序中运行函数

Running a function in chrome extension on double click/select of a word

本文关键字:程序 运行 函数 扩展 chrome 双击 选择 单词时      更新时间:2023-09-26

每当我双击一个单词/选择它时,我都会尝试触发通知。在网上找到了几个例子,但我仍然无法让我的例子工作:

清单:

{
  "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"]
  }
 },

我想要实现的目标:每当他们进入任何页面选择一个单词时,它都会触发该函数。稍后,我希望将其用于特定页面。:)

已尝试: 如何保持 chrome 扩展程序的事件侦听器的实时性?

Chrome扩展程序双击某个字词

https://github.com/max99x/inline-search-chrome-ext

两者都不能像我想要的那样工作。 :(

解决方案

您似乎对背景页面和内容脚本感到困惑。事实上,你的background.js是一个content script,尽管它的名字是"背景"。虽然chrome.notifications api只能在background page中调用,但尝试注释displayPrice函数将使你的代码正常工作。

下一步

看看上面的教程,dblclick事件触发器,使用消息传递与后台页面通信,并在后台页面调用chrome.notications api。

并且

以下代码用于 chrome 应用,而不是 chrome 扩展程序。

"app": {
    "background": {
      "scripts": ["background.js", "assets/jquery.min.js"]
    }
 },