[英]Javascript chrome extension not clicking button with click()
[英]Clicking a button with Javascript on an official website (chrome extension)
我正在嘗試創建一個chrome擴展程序,該擴展程序使用DOM.click()方法單擊網站上的按鈕。 ( https://www.w3schools.com/jsref/met_html_click.asp )
編輯:此chrome擴展程序的目的是創建一個鍵盤快捷方式,以在觀看外語視頻時打開/關閉英語字幕。 如果要嘗試理解沒有字幕的語言,則在需要時必須使用鼠標並拖動鼠標以打開菜單以打開字幕。 我想創建一個可以立即打開字幕的鍵盤快捷鍵。 此類網站的示例是( https://www.ondemandkorea.com/ask-us-anything-e102.html )
<button type="button" class="jw-reset jw-settings-content-item" role="menuitemradio" aria-checked="false">English</button>
這是我嘗試使用Javascript單擊的網站上的按鈕
在我的代碼中,我有一個窗口偵聽器,等待特定的網站加載。 然后,要找到我要單擊的按鈕,我調用document.getElementsByClassName(“ Class Name”),並在返回的元素數組中查找一個說英語的按鈕,並將其保存到var englishButton中 。 我添加了另一個偵聽器,該偵聽器監聽要按下的鍵盤鍵,然后依次按下englishButton 。
但是,當我單擊快捷鍵時, englishButton.click(); 似乎什么也沒做。 我知道找到了正確的英文按鈕,並且我的shortcutKey Listener通過使用console.log()語句工作。
我似乎無法理解為什么按鈕無法單擊。
編輯:將buttonListener添加到代碼中后,英文按鈕畢竟會單擊,但不會打開視頻的字幕
這是我的代碼。
/*
Looking for the subtitle button that states "English"
*/
var englishButton;
window.addEventListener("load", function(event) {
var buttonList = document.getElementsByClassName('jw-reset jw-settings-content-item');
for (var i = 0, len = buttonList.length; i < len; i++){
if(buttonList[i].textContent === "English") {
englishButton = buttonList[i];
break;
}
}
englishButton.addEventListener('click', function() {
console.log('englishButton clicked!');
});
/*
Event Listener that detects when the shortcut key is hit.
When the shortcut Key is hit. It will simulate a mouse click on the subtitle button
*/
document.addEventListener('keyup', function(e){
if(e.key === shortcutKey){
console.log('shortcut pressed')
englishButton.click();
}
}
);
});
我建議您使用jQuery,以便可以使用諸如keyup()或keydown()之類的函數,以便可以在按下某個鍵時進行監聽。 如果我們只想監視DOM元素而不使用類,那么更好的做法是按id檢查元素。
將所有代碼移到您的load
偵聽器中:
https://codepen.io/ryanpcmcquen/pen/EOerPM?editors=1011
window.addEventListener("load", function(event) { /* Looking for the subtitle button that states "English" */ var englishButton; // console.log('Website loaded. englishButton:', englishButton); var buttonList = document.getElementsByClassName("jw-reset"); for (var i = 0, len = buttonList.length; i < len; i++) { if (buttonList[i].textContent === "English") { englishButton = buttonList[i]; // console.log("englishButton found", englishButton); break; } } // console.log("End of window-load's callback. englishButton:", englishButton); /* Event Listener that detects when the shortcut key is hit. When the shortcut Key is hit. It will simulate a mouse click on the subtitle button */ document.addEventListener("keyup", function(e) { console.log( "Inside document-keyup's callback. englishButton:", englishButton ); if (e.key == "z") { //Logic to press the subitle button console.log( "Key matched: ", e.key, "Now click button. englishButton:", englishButton ); englishButton.click(); console.log("Shortcut Key"); } else { console.log("Random Key"); } }); englishButton.addEventListener("click", function() { console.log("englishButton clicked!"); }); });
<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <button type="button" class="jw-reset">English</button> </body> </html>
但是您的代碼中仍有一些可以改進的地方,因此讓我們看一下代碼的“更現代”版本(代碼中的注釋):
// Using the `window` `load` event is fine, but // you should prefer the `document` `DOMContentLoaded` // event when possible, since it fires when the DOM // has been constructed, while `load` means all assets have fully loaded (images). // For your case since you are relying only on elements, // `DOMContentLoaded` is a better choice. document.addEventListener("DOMContentLoaded", function(event) { /* Looking for the subtitle button that states "English" */ var englishButton; // Use `querySelectorAll` since it is more dynamic and // will accept any type of selector. Also, for loops // are avoided in most modern JavaScript because // they create scoping and off-by-one errors. // Since you want to break out of the loop here, // we will use `.some()`. `Array.prototype.slice.call()` // converts the NodeList returned by `querySelectorAll` // into an Array. Array.prototype.slice.call(document.querySelectorAll(".jw-reset")).some( function (button) { if (button.textContent === 'English') { englishButton = button; return true; } } ); /* Event Listener that detects when the shortcut key is hit. When the shortcut Key is hit. It will simulate a mouse click on the subtitle button */ document.addEventListener("keyup", function(e) { console.log( "Inside document-keyup's callback. englishButton:", englishButton ); if (e.key === "z") { //Logic to press the subitle button console.log( "Key matched: ", e.key, "Now click button. englishButton:", englishButton ); englishButton.click(); console.log("Shortcut Key"); } else { console.log("Random Key"); } }); englishButton.addEventListener("click", function() { console.log("englishButton clicked!"); }); });
<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <button type="button" class="jw-reset">English</button> </body> </html>
在您對問題的評論中,您確認該按鈕實際上是在觸發點擊。 因此,您遇到的問題是通過點擊產生預期的結果。 可以打開和關閉英文字幕。 這里有一個更好,更簡單,更可靠的替代方案。
該網站使用JW Player播放其視頻。 他們有一個文檔齊全且開放的API( https://developer.jwplayer.com/jw-player/docs/developer-guide )。
您要做的就是這樣
jwplayer().setCurrentCaptions(X)
X是您要從特定視頻中可用的所有字幕列表中選擇的字幕選項的索引號。
在您的示例視頻中,列表只有兩項:
0:關閉
1:英語
所以打開英語:
jwplayer().setCurrentCaptions(1)
並關閉所有字幕:
jwplayer().setCurrentCaptions(0)
如果從一個視頻到另一個視頻,索引會有所不同,則需要首先獲取可用字幕的列表,然后找到英語的索引號。
let allCaptions = jwplayer().getCaptionsList();
englishCaptionIndex = allCaptions.findIndex(caption => caption.label == 'English');
而已。
您可以使用API進行各種有趣的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.