我正在创建我的第一个Firefox扩展。这个想法很简单:
我不知道#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"
}
}
有几种方法可以完成。
这里是不需要“ 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()
来计数列表