LoginSignup
4
4

More than 5 years have passed since last update.

WebExtensionのpopupやbackgroundでcurrentTabを取得する場合は代わりにqueryを使う

Posted at

まとめ

  • popupやbacngroundのスクリプトでtabs.getCurrent()は利用不可(undefinedが返る)
    • Promiseの失敗には入らず成功としてundefinedが取得できるので注意
  • tabs.query()は利用可能なので、プロパティの組み合わせでカレントタブを特定することで代用

    • 組み合わせの一例は{ currentWindow:true, active:true }{ windowId: browser.windows.WINDOW_ID_CURRENT, active:true }
    • queryなので結果は一件だが常に配列で返るのが少し手間
    • currentcurrentTabプロパティがあるわけではないので注意
  • おそらくAndroid版のpopupは別タブで開かれるのでcurrentがpopupになる可能性がある…(未調査)

    • よってこの記事はPC版限定とする

環境

  • Ubuntu
  • Firefox 65.0 64bit
  • 一時的な拡張機能として読み込み

公式に明記されている

tabs.getCurrent() - Mozilla | MDN

You can call this function in contexts where there is a browser tab, such as an options page. If you call it from a background script or a popup, it will return undefined.

Google翻訳

この機能は、 オプションページなどのブラウザタブがあるコンテキストで呼び出すことができます 。 バックグラウンドスクリプトまたはポップアップからそれを呼び出すと、undefinedが返されます。

コード

popupで動かすとする。

tabs.getCurrent()を使った失敗例 undefinedが返る

browser.tabs.getCurrent().then(tab => {
  console.log('getCurrent', tab) // undefined
}, error => {
  // ここには入らない
  console.error(error)
})

代用コード

tabs型には直接Currentプロパティはないが、組み合わせや別プロパティからカレント情報を取得して一意に特定することができる。

どちらも結果は同じ。なはず。

browser.tabs.query({ currentWindow:true, active:true }).then(tabs => {
  for (tab of tabs) {
    console.log('currentWindow', tab)
  }
}, error => {
  console.error(error)
})

browser.tabs.query({ windowId: browser.windows.WINDOW_ID_CURRENT, active:true }).then(tabs => {
  for (tab of tabs) {
    console.log('browser.windows.WINDOW_ID_CURRENT', tab)
  }
}, error => {
  console.error(error)
})

参考


4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4