前提
Chrome Extention(拡張機能)で chrome.scripting.executeScript 関数で実行した関数の結果が undefined になってしまう。
実現したいこと
- chrome.scripting.executeScript 関数で別の関数からの戻り値を取得したい。
※ 最終的な目的として、chromeのアクティブなタブ内の、動的に変化する要素をjavascriptでクリックするなどの操作を自動化したいと考えています。
executeScript 関数でなくても上記の目的を実現できるものがあれば、何を使えばいいかだけでも良いのでご教示いただきたいです。
発生している問題・エラーメッセージ
background.js:28 Cannot read properties of undefined (reading '0')
background.js:25行目の console.log で例外が発生しています。
res[0].result は myFunction の戻り値「1234」が入る認識なのですが、実動作は「undefined」となっているようです。
該当のソースコード
background.js
javascript
1console.log('background.js'); 2excute_script_test() 3/////////////////////////////////////////////////// 4function myFunction() { 5 console.log('myFunction') 6 return 1234; 7} 8 9function excute_script_test(){ 10 try{ 11 console.log('excute_script_back1 begin') 12 chrome.tabs.query({ active: true }, function (tabs) { 13 let tab = tabs[0]; 14 console.log('tab.id = ' + tab.id); 15 try{ 16 chrome.scripting.executeScript( 17 { 18 target: { tabId: tab.id }, 19 function: myFunction 20 }, 21 (res) => { 22 try{ 23 console.log('excute_script_back1 result'); 24 console.log(res[0].result) 25 } catch(e){ 26 console.log('result ERROR:') 27 console.log(e.message); 28 } 29 }); 30 } catch(e){ 31 console.log('chrome.tabs.query ERROR:') 32 console.log(e.message); 33 } 34 }); 35 } catch(e){ 36 console.log('excute_script_back1 ERROR:'); 37 console.log(e); 38 } 39 console.log('excute_script_back1 end'); 40}
popup.html
html
1<!DOCTYPE html> 2<html lang="ja"> 3 <head> 4 <meta charset="utf-8"> 5 <title>Link Maker</title> 6 </head> 7 <body> 8 <script src="js/lib/jquery-3.6.0.min.js"></script> 9 <div id="main_contents"> 10 <p>test_popup</p> 11 </div> 12 </body> 13</html>
manifest.json
json
1{ 2 "name": "excute scripting test", 3 "version": "0.0.1", 4 "description": "excute scripting test.", 5 "action": { 6 "default_icon": {"16" : "icon_16x16.png"}, 7 "default_title": "excute scripting test", 8 "default_popup": "popup.html" 9 }, 10 "icons": { 11 "16" : "icon_16x16.png", 12 "48" : "icon_48x48.png", 13 "128": "icon_128x128.png" 14 }, 15 "permissions": ["activeTab","tabs","storage","unlimitedStorage","scripting"], 16 "author": "watashi", 17 "manifest_version":3 , 18 "background": { 19 "service_worker": "background.js" 20 }, 21 "content_scripts": [ 22 { 23 "matches": ["<all_urls>"], 24 "js": ["js/popup.js"] 25 } 26 ] 27}
実行結果(DevToolsメッセージ)
background.js:1
1background.js:12 excute_script_back1 begin 2background.js:40 excute_script_back1 end 3background.js:15 tab.id = 1381359488 4background.js:24 excute_script_back1 result 5background.js:27 result ERROR: 6background.js:28 Cannot read properties of undefined (reading '0')
試したこと
パッケージの削除→インストールを行いましたが、うまくいきませんでした。
検索して色々なサイトを拝見したのですが、自己解決できず、、、すみませんがよろしくお願いします。
補足情報(FW/ツールのバージョンなど)
- Windows10
- Chrome Extention(拡張機能)
- Google Chrome バージョン: 105.0.5195.102(Official Build) (64 ビット)
Chromeのバージョンは1つまえのもの(104.0.5112.102)でもNGでした。

回答1件
あなたの回答
tips
プレビュー