11
6

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拡張機能:onMessage.addListenerに登録する関数にasyncを指定するとコールバック関数が実行されない

Last updated at Posted at 2018-01-06

状況

content_script.js
chrome.runtime.sendMessage({type: 'sendMessage'}, response => {
  console.log('コールバック');
});
background.js
chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
  if (message.type === 'sendMessage') {
    await aaa();
    sendResponse({type: 'sendResponse'});
    return true;
  }
});

background.jsでchrome.runtime.onMessage.addListenerに登録する関数にasyncを指定すると、return true;を実行しても返り値がPromiseになってしまう。そのため、content_script.js側のコールバック関数が意図したタイミングで実行されない。

対処法

content_script.js
chrome.runtime.sendMessage({type: 'sendMessage'});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'sendResponse') {
    console.log('コールバック');
  }
});
background.js
chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
  if (message.type === 'sendMessage') {
    await aaa();
    chrome.tabs.sendMessage(sender.tab.id, {type: 'sendResponse'});
  }
});

chrome.runtime.sendMessageのコールバック関数は使わず、chrome.tabs.sendMessageで新しくメッセージを送信する。

11
6
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
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?