如何获得浏览器扩展弹出窗口以显示变量

问题描述 投票:1回答:1

我正在创建我的第一个Firefox扩展。这个想法很简单:

  1. 查找页面上的所有列表。
  2. 在其周围放置边框。
  3. 将列表数记录到变量中。
  4. 在弹出窗口中显示此变量。

我不知道#4,在弹出窗口中显示变量。请帮助初学者!

这是我的代码:

// Variables
const $ulList = document.querySelectorAll('ul')
const $olList = document.querySelectorAll('ol')
const $dlList = document.querySelectorAll('dl')

// Finds all list elements
function findLists($ulList, $olList, $dlList) {
    // Gives them a pink border
    for (const $ul of $ulList) {
        $ul.style.border = "5px solid pink";
    }
    for (const $ol of $olList) {
        $ol.style.border = "5px solid pink";
    }
    for (const $dl of $dlList) {
        $dl.style.border = "5px solid hotpink";
    }
}

// Records length of all lists
var $ulListLength = $ulList.length
console.log('ul Lists: ' + $ulListLength)
var $olListLength = $olList.length
console.log('ol Lists: ' + $olListLength)
var $dlListLength = $dlList.length
console.log('dl Lists: ' + $dlListLength)

// The total number of lists on the page
$totalListsLength = $ulListLength + $olListLength + $dlListLength
console.log('Total lists: ' + $totalListsLength)

这里是manifest.json。请注意,pop-display.js当前为空。

{
  "description": "QA common style mistakes for Canada.ca style guide.",
  "manifest_version": 2,
  "name": "WebPubQA",
  "version": "1.0",
  "homepage_url": "https://github.com/sinc0115/web-pub-qa",
  "icons": {
    "48": "icon/outline_highlight_black_48dp.png"
  },

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["webPubQA.js", "pop-display.js"]
    }
  ],

   "permissions": [
    "activeTab"
  ],

  "background": {
        "scripts": ["pop-display.js"]
    },

  "browser_action": {
    "default_icon": "icon/outline_highlight_black_48dp.png",
    "default_title": "Web Pub QA",
    "default_popup": "index-pop.html"
  }

}
javascript firefox popup firefox-addon firefox-webextensions
1个回答
0
投票

有几种方法可以完成。

这里是不需要“ content_scripts”才能起作用的一个:

// in popup.js
const code = `
const ul = document.querySelectorAll('ul');
const ol = document.querySelectorAll('ol');
const dl = document.querySelectorAll('dl');

// add border to all
[...ul, ...ol, ...dl].forEach(item => item.style.border = '5px solid pink');

// Records length of all lists
const ulLen = ul.length;
const olLen = ol.length;
const dlLen = dl.length;
const total = ulLen + olLen + dlLen;

console.log('ul Lists: ' + ulLen);
console.log('ol Lists: ' + olLen);
console.log('dl Lists: ' + dlLen);
console.log('Total lists: ' + total);

// return value is passed back to the tabs.executeScript
return total; 
`;

// tabs.executeScript without tabId inject into active tab
chrome.tabs.executeScript({code}, result => {
  // result is array, the value passed is result[0]
  // do whatever with result[0]
});

另一种方法是:

  • 添加内容脚本
  • 内容脚本中有runtime.onMessage.addListener()
  • 从弹出窗口发送tabs.sendMessage()来计数列表
  • 等待从内容脚本返回的消息以在弹出窗口中显示总计
© www.soinside.com 2019 - 2024. All rights reserved.