首页 > 解决方案 > 如何从“window.getSelection”获取字符串以及如何使用“window.open”修复打开新标签?

问题描述

我正在为 Firefox(我使用 ver.65)创建扩展,它假设在 Filmweb 网站(相当于 IMDB)上搜索电影的标题。通过使用任何网站上的选择并结合 Filmweb 的搜索端地址,然后在新选项卡上转到该地址,就会发生这种情况。

我尝试使用document.getSelection而不是window.getSelection但它不起作用。

filmwebExt.js

const contextMenuItem = {
    id: "search-on-Filmweb",
    title: "Search on Filmweb",
    contexts: ["selection"]
};

function getSelectionText() {
    console.log('window.getSelection: ',window.getSelection());
    var text = "true";
    if (window.getSelection()) {
        text = window.getSelection().toString();
        console.log(text); //empty in debbuging console
    } else if (document.selection && document.selection.type !== "Control") {
        text = document.selection.createRange().text;
    }
    console.log(text); //empty in debbuging console
    return text;
}
console.log('second window.getSelection: ',window.getSelection());
browser.contextMenus.create(contextMenuItem);
browser.contextMenus.onClicked.addListener(function (info) {

    const selectedText = getSelectionText();
    const url = 'https://www.filmweb.pl/search?q=';
    const fullUrlAddress = url + selectedText;
    if (info.menuItemId === "search-on-Filmweb") {
        console.log('comparison: ',info.menuItemId === "search-on-Filmweb");
        console.log("selectedText ",selectedText," fullUrlAddress ",fullUrlAddress);
        window.open(fullUrlAddress, '_blank');
    }
});

清单.json

{
  "manifest_version": 2,
  "name": "Filmweb_Search",
  "version": "1.0",
  "description": "Adds Filmweb search option in context menu",
  "applications": {
    "gecko": {
      "id": "wisznu@gmail.com"
    }
  },
  "background": {
    "scripts": [
      "filmwebExt.js"
    ]
  },
  "icons": {
    "48": "icons/Filmweb_icon48x48.png",
    "96": "icons/Filmweb_icon96x96.png"
  },
  "content_scripts": [
    {
      "matches": [
        "*://*/*"
      ],
      "js": [
        "filmwebExt.js"
      ]
    }
  ],
  "permissions": [
    "tabs",
    "activeTab",
    "<all_urls>",
    "contextMenus"
  ]
}

目前,上下文菜单项正确显示在上下文菜单中,但调试控制台显示window.getSelection()在对象中返回空值,在window.getSelection().toString()中返回空字符串

调试控制台日志

标签: javascriptfirefox-addon

解决方案


如果 Firefox Add-On 的基础结构仍然与几年前相似,那么这里的问题是您无法从上下文菜单所在的过程访问文档的选择。

我相信正是出于这个原因info添加了对象,以便您可以在代码运行的过程中获得所需的信息。该对象info有一个名为 的属性selectionText,这就是您必须使用的。

对于打开一个新标签,最好使用 tabs API。

因此,总而言之,您的filmwebExt.js文件如下所示:

const contextMenuItem = {
  id: "search-on-Filmweb",
  title: "Search on Filmweb",
  contexts: ["selection"]
};

browser.contextMenus.create(contextMenuItem);
browser.contextMenus.onClicked.addListener(info => {
  if (info.menuItemId === "search-on-Filmweb") {
    const url = "https://www.filmweb.pl/search?q=" + info.selectionText;

    browser.tabs.create({ url });
});

推荐阅读