簡體   English   中英

如何從“ window.getSelection”獲取字符串以及如何使用“ window.open”修復打開新標簽頁的問題?

[英]How to get string from 'window.getSelection' and how to fix opening new tab by using 'window.open'?

我正在為Firefox(我使用版本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');
    }
});

的manifest.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()的空字符串

調試控制台日志

如果Firefox加載項的基礎結構仍與幾年前相似,則這里的問題是您無法從上下文菜單所在的過程訪問文檔的選擇。

我相信正是出於這個原因,添加了info對象,以便您可以在運行代碼的過程中獲得所需的信息。 對象info具有一個名為selectionText的屬性,這就是您必須使用的屬性。

對於打開新標簽頁,最好使用標簽頁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 });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM