2
2

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 3 years have passed since last update.

[Chrome Extension]スクリプト間のデータ受け渡し

Posted at

こんにちは Takeです。

Chrome Extensionを作成するにあたり主なパーツが以下の3つです。

  • Content Script
  • Event/Background Page
  • Popup

今回はこの3つの間のデータ受け渡しについてメモ程度に書きます。

※あくまで例であって作成する拡張機能の内容によってケースバイケースです。

1 Content → Event/Background Page

今回は例として開いているページのURLを取得しEvent/Background Pageへ渡します。

データを渡す側

content.js
const getPageTitle = function () {
    var url = location.href;
    return url
}

chrome.runtime.sendMessage(getPageTitle(), function (response) {
    return true;
})

データを受け取る側

event.js
hrome.runtime.onMessage.addListener(function (info,sendResponse) {
    console.log(info)
}

2 Event/Background Page → Popup

データを渡す側

event.js
var value = "sample";

データを受け取る側

popup.js
  console.log(chrome.extension.getBackgroundPage().value)

3 Popup → Content

データを渡す側

popup.js
const SampleFunc = function () {
  return "Sample";
}

chrome.runtime.sendMessage(SampleFunc(), function (response) {
})

データを受け取る側

content.js
  chrome.runtime.onMessage.addListener(function (message) {
    console.log(message);
    return true;
});
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?