LoginSignup
wagateee
@wagateee (itsuki wagatsuma)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Chrome拡張機能作成時「Unchecked runtime.lastError」が起きる

解決したいこと

Chrome拡張機能を自作したいです。

発生している問題・エラー

検証ツールにて

Unchecked runtime.lastError: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received

スクリーンショット 2023-12-26 221902.png

スクリプトの全体像

manifest.json
{
  "manifest_version": 3,
  "name": "拡張機能名",
  "version": "3.0",
  "description": "説明文",
  "icons": {
    "48": "icon.png"
  },
  "permissions": ["activeTab"],
  "action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}
popup.js
document.getElementById('mildifyButton').addEventListener('click', function() {
console.log("hoge")
  chrome.runtime.sendMessage({ action: 'mildifyText' });
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === 'mildifyText') {
    alert("A")

      chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { action: 'mildifyText' });
      });  
    }
    alert("B")
    return true;
  });
content.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  alert("C")
  if (request.action === 'mildifyText') {
    mildifyText();
  }
  return true
});
alert("D")
function mildifyText() {
  const elements = document.querySelectorAll('*');

  elements.forEach(function(element) {
    if (element.nodeType === Node.TEXT_NODE) {
      element.nodeValue = replaceOffensiveText(element.nodeValue);
    }
  });
}

function replaceOffensiveText(text) {
  //ここで各テキストに対して処理を行う
}

スクリーンショット 2023-12-26 222438.png

自分で試したこと

console.logではありませんが、要所要所にAlertを設置したところ、alert("D")つまり、content.jsの読み込みまではうまくいっているようでした。
別で、popup.jsに仕込んだconsoleも表示されます。
おそらく、popup.js > chrome.runtime.sendMessage と background.jsとの間の連携がうまくいっていないようです、
ちなみに、拡張機能画面では以下のような表示がされています
スクリーンショット 2023-12-26 222949.png

0

1Answer

https://developer.mozilla.org/ja/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage#sendresponse_%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%9F%E9%9D%9E%E5%90%8C%E6%9C%9F%E3%81%AE%E5%BF%9C%E7%AD%94%E3%81%AE%E9%80%81%E4%BF%A1
https://www.mitsuru-takahashi.net/blog/chrome-extension-response/

chrome.runtime.onMessage.addListenerで設定したコールバック関数が true を返すときは
後で sendResponse を使うので、ブラウザにコールバック関数が終了してもポートを閉じないようにする指示です
なので sendResponse を使わないなら、コールバック関数は true を返してはいけません

1

Your answer might help someone💌