Q&A
前提
chrome拡張機能の開発をしています。
contents scriptで非同期処理を行い、popupに非同期処理の結果を送りたいのですが、うまく機能していないようなので質問させていただきます。
発生している問題
下に記述したコードの、contents-script.ts:12
のconsole.log(r)
では1
と出力されることを確認しました。
popup.ts:10
のconsole.log(item)
ではundefined
となりました。
popup.ts:10
で1
が出力されるようにしたいです。
該当のソースコード
contents-script.ts
typescript
1const asyncTest = async () => { 2 return new Promise((resolve) => { 3 setTimeout(() => { 4 resolve(1) 5 }, 1000) 6 }) 7} 8 9chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){ 10 if(request.message == "popup.load_start"){ 11 asyncTest().then((r) => { 12 console.log(r); 13 sendResponse(r) 14 }) 15 } 16}); 17 18export {} 19
popup.ts
typescript
1function Hoge() { 2 const getMessage = () => { 3 chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { 4 if (!tabs[0].id) { 5 return; 6 } 7 chrome.tabs.sendMessage( 8 tabs[0].id, 9 { message: 'popup.load_start' }, 10 function (item) { 11 console.log(item) 12 } 13 ); 14 }); 15 }; 16 // ... 17 return ( 18 <button onClick={getMessage}>読み込み</button> 19 ) 20}
ご指導お願いいたしますm(__)m
回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2023/03/16 02:48