8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

chrome.tabs.executeScriptのファイル実行に引数を渡す

Last updated at Posted at 2019-01-28

はじめに

Chromeエクステンションの開発時、タブを指定してコードを実行したいときは
以下のようにしますが、これでは引数を与えることができません。

chrome.tabs.executeScript(tab.id, {
  file: "src/test.js"
})

解決策

chrome.tabs.executeScriptをネストして、最初のコードで渡したい値をゴニョゴニョします。
ゴニョゴニョした内容は次のfile: "src/test.js"内に引き継がれます。

chrome.tabs.executeScript(tab.id, {
    code: 'let config = 1;'
  }, () => {
    chrome.tabs.executeScript(tab.id, {
        file: "src/test.js"
    })
  })
})

// src/test.js
console.log(config) // => 1

引数がオブジェクト型のような複雑なものの場合はJSON.stringifyを使います。

let config = {foo: 'bar'}

chrome.tabs.executeScript(tab.id, {
    code: 'let config = ' + JSON.stringify(config)
  }, () => {
    chrome.tabs.executeScript(tab.id, {
        file: "src/test.js"
    })
  })
})

// src/test.js
console.log(config) // => {foo: 'bar'}
8
9
1

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
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?