2017-07-15 32 views
0

我正在將我的擴展從SDK遷移到WebExtensions,並且我無法找到背景腳本和側邊欄之間的通信方式。這個想法是在用戶點擊一個上下文菜單時傳遞用戶突出顯示的文本和一些額外的信息。我需要這個選擇在「選定文本」輸入複製,但我不能操縱從腳本工具條的DOM ...:(如何在Firefox WebExtensions中將背景與側欄腳本進行通信? (反之亦然)

browser.contextMenus.create({ 
    id: "save-highlighted-data", 
    title: browser.i18n.getMessage("save-data"), 
    contexts: ["all"], 
    onclick: function(info,tab){ 

    //I got the highlighted data 
    console.log("Selected text: " + info.selectionText); 

    browser.sidebarAction.setPanel({ 
     panel: browser.extension.getURL("/sidebar/annotation.html") 
    }).then(function(){ 

     //In this context, "this" = the chrome window. But I can not change the document 
     // of the sidebar 
     //console.log("window", this.document.querySelector("#selected-text")); 
    }); 
    }, 
    command: "_execute_sidebar_action" //This toggles the sidebar 
}); 

任何想法,我檢查在側邊欄的例子GitHub庫,但他們只是打開一個側邊欄與側邊欄切換行動("_execute_sidebar_action"

+0

您是否嘗試過'runtime.sendMessage()'和'runtime.onMessage.addListener()'? 您還可以從側邊欄訪問DOM,但涉及使用'tabs.query()'來查找活動選項卡,因爲邊欄沒有附加到特定選項卡。 – erosman

+0

@erosman謝謝,這就是答案。它適用於運行時。你願意把它作爲答案嗎? PS:最後一個問題>如果側邊欄沒有標籤,如何使用tabs.query()?謝謝! – gal007

回答

0

擴展的背景,內容,工具條等腳本可以相互使用runtime.sendMessage()runtime.onMessage.addListener()

AFAIK溝通不溝通,有在側邊欄和內容DOM之間沒有任何直接連接電子時刻。

您可以使用tabs.query()得到活動標籤(這是可見選項卡)或任何其他標籤

function logTabs(tabs) { 
    for (let tab of tabs) { 
    // tab.url requires the `tabs` permission 
    console.log(tab.url); 
    } 
} 

function onError(error) { 
    console.log(`Error: ${error}`); 
} 

var querying = browser.tabs.query({currentWindow: true, active: true}); 
querying.then(logTabs, onError); 

或者

chrome.tabs.query({currentWindow: true, active: true}, function (tabs) { 
    // tabs[0] is the active tab 
}); 

然後,您可以使用tabs.executeScript()tabId你從tabs.query()(即tabs[0].id)得到的JavaScript代碼注入頁面(DOM)並與我交互ts DOM。

+0

非常感謝你! – gal007

相關問題