2017-07-15 2 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:最後の1つの質問>サイドバーにタブがない場合、どのようにtabs.query()を使用できますか?ありがとう! – gal007

答えて

0

拡張の背景、内容、サイドバーには、などのスクリプトがruntime.sendMessage()runtime.onMessage.addListener()

私の知る限りを使用して相互に通信することができない多くの通信にサイドバーを開きますサイドバーとコンテンツ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 
}); 

その後、tabIdでtabs.executeScript()を使用することができますtabs.query()(つまりtabs[0].id)からJavaScriptコードをページ(DOM)に挿入し、iとやりとりするDOM。

+0

ありがとう! – gal007

関連する問題