我想呼叫一個在擴展的內容腳本中實作的函式,它從網頁中獲取選定的文本,從后臺腳本中的一個函式中呼叫,該函式稍后將在連接到選單項的偵聽器中呼叫。
這可能嗎?最短的方法是什么?
以下是相關的代碼片段:
清單檔案
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
內容.js
var text = "";
function highlightedText() {
text = content.getSelection();
}
背景.js
function listenerFunction() {
highlightedText();
/* Doing various stuff that have to use the text variable */
}
browser.menus.onClicked.addListener((info, tab) => {
highlightedText();
});
顯然,上面的代碼不起作用,因為現在可以從后臺腳本中看到“突出顯示”的功能。
那么,使代碼作業的最快/最短方法是什么?
uj5u.com熱心網友回復:
好的。我不得不從我自己的一個私人擴展中提取這個,但要點是:
在后臺腳本中設定選單,并為 onclick 屬性分配一個函式:
browser.menus.create({
id: 'images',
title: 'imageDownload',
contexts: ['all'],
onclick: downloadImages
}, onCreated);
仍然在同一個腳本中獲取當前選項卡資訊,并向內容腳本發送訊息。
function getCurrentTab() {
return browser.tabs.query({ currentWindow: true, active: true });
}
async function downloadImages() {
const tabInfo = await getCurrentTab();
const [{ id: tabId }] = tabInfo;
browser.tabs.sendMessage(tabId, { trigger: 'downloadImages' });
}
內容腳本偵聽訊息:
browser.runtime.onMessage.addListener(({ trigger }) => {
if (trigger === 'downloadImages') doSomething();
});
處理完成后,將新訊息傳遞回后臺腳本。
function doSomething() {
const data = [1, 2, 3];
browser.runtime.sendMessage({ trigger: 'downloadImages', data });
}
在一個單獨的后臺腳本中,我有如下內容:
browser.runtime.onMessage.addListener(function (data) {
const { trigger } = data;
if (trigger === 'downloadImages') ...
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/349259.html
標籤:javascript 谷歌浏览器 火狐 谷歌浏览器扩展 火狐插件
