LoginSignup
5
4

More than 3 years have passed since last update.

Unchecked runtime.lastError: The message port closed before a response was received. を回避した一例

Last updated at Posted at 2020-08-05

初めに

自作chrome拡張機能の制作中、とある処理をすると必ずこのエラーが出て気になっていたのですが、一行追加したら出なくなったので記念に残しておきます。

どんな処理かざっくり言いますと、
アクティブページで得た情報を、ポップアップメニューを介して拡張機能専用ウィンドウへ送信するものです。
完了したタイミングで、ポップアップ側にてエラーが出てました。

エラーを出していたコード

アクティブページ側は省略。

popup.js
const sendMessage = (id, msg) => new Promise( r => chrome.tabs.sendMessage( id, msg, s => r(s) ) );
//アクティブページの情報を取得
const res = await sendMessage( tab_id, { ... } );
//受け取ったデータを専用ウィンドウへ送信
sendMessage( window_tab_id, res );

送信後に行う処理も無いので投げっぱなし

app_window.js
chrome.runtime.onMessage.addListener( (message, sender, sendResponse) => {
    doSomething(message);
    return;
});

エラーが出なくなったコード

popup.jsは変更なしなので省略。
受信側に一行追加します。

app_window.js
chrome.runtime.onMessage.addListener( (message, sender, sendResponse) => {
    doSomething(message);
    sendResponse(); // new
    return;
});

特に何もなくても返信はしましょう、という事でしょうか。

最後に

あくまで一例です。

5
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
5
4