はじめまして。自作でGoogleの拡張機能を製作しています。
そこでEventListenerの中である要素を取得したいんですが、取得できません。
その原因と解決策をご回答いただけたら幸いです。
発生している問題・エラーメッセージ
拡張機能の「自動いいね開始」ボタンを押下したら、あるWebサイトのいいねボタンを取得したいが、なぜか取得できずにnullが返却される。
EventListenerの外で取得するとちゃんと取得される。
逆にEventListener内だと要素が取得できずにnullが返却されてしまう
該当のソースコード
javascript
1// インターバルの時間(ミリ) 2const INTERVAL = 500; 3 4// タイムアウトになるまでの最大処理回数 5const TIMEOUT_LIMIT = 5; 6 7document.addEventListener("DOMContentLoaded", function() { 8 document.getElementById("autoGoodBtn").addEventListener("click", function() { 9 let notice = ""; 10 // TODO: もし不具合で無限ループ入ったらえぐいから入れとく。 11 let testCnt = 0; 12 let exec_num = 0; 13 14 while (true) { 15 // ボタンを取得 16 let btnType = document.getElementById("btnType"); 17 18 // ボタンが取得できていなかったら処理を終了する 19 if (btnType == null) { 20 notice = `処理が完了しました。今回処理した件数は「${exec_num}件」です`; 21 break; 22 } 23 24 // 処理回数 25 let timeoutCnt = 0; 26 27 let timerId = setInterval(() => { 28 let wait = document.querySelector(".wait"); 29 30 // waitが消えていたらいいねをクリック 31 if (wait == null) { 32 btnType.click(); 33 exec_num++; 34 clearInterval(timerId); 35 } else { 36 timeoutCnt++; 37 } 38 39 // タイムアウト 40 if (TIMEOUT_LIMIT <= timeoutCnt) { 41 notice = "タイムアウト:ネットワーク状況が悪いようです。"; 42 clearInterval(timerId); 43 } 44 }, INTERVAL); 45 46 // TODO: もし不具合で無限ループ入ったらえぐいから入れとく。 47 if (50 < testCnt) { 48 alert("無限ループ入ったで"); 49 break; 50 } 51 } 52 53 // logを出力 54 document.getElementById("log").innerHTML = notice; 55 }); 56}); 57
html5
1<html lang="en"> 2 <head> 3 <meta charset="UTF-8" /> 4 <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 5 <meta http-equiv="X-UA-Compatible" content="ie=edge" /> 6 <style> 7 body { 8 width: 100px; 9 } 10 </style> 11 </head> 12 <body> 13 <button id="autoGoodBtn">自動いいね開始</button> 14 <div> 15 <h2>ログ</h2> 16 <div id="log"></div id="log"> 17 </div> 18 <script src="autoGood.js"></script> 19 </body> 20</html> 21
ご回答よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。