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
スクリプトの全体像
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) {
//ここで各テキストに対して処理を行う
}
自分で試したこと
console.logではありませんが、要所要所にAlertを設置したところ、alert("D")
つまり、content.jsの読み込みまではうまくいっているようでした。
別で、popup.jsに仕込んだconsoleも表示されます。
おそらく、popup.js > chrome.runtime.sendMessage と background.jsとの間の連携がうまくいっていないようです、
ちなみに、拡張機能画面では以下のような表示がされています
1