Как получить всплывающее окно расширения браузера для отображения переменной - PullRequest
1 голос
/ 18 февраля 2020

Я создаю свое первое расширение 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)

Вот манифест. 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"
  }

}

1 Ответ

0 голосов
/ 19 февраля 2020

Есть несколько способов, которыми это можно сделать.

Вот тот, который не требует "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() из всплывающего окна для подсчета LIST
  • ждать сообщение обратно из скрипта контента для отображения итогов во всплывающем окне
...