[英]Click doesn't work on this Google Translate button?
我正在創建一個Tampermonkey用戶腳本,它會自動點擊谷歌翻譯網站上的“星標”按鈕並保存我的搜索,以便我以后可以查看它們並進行排練。
這是我到目前為止所得到的:
// @match https://translate.google.com/#en/de/appetit/
var el = document.getElementById("gt-pb-star");
setTimeout(function(){
el.click();
},4000);
我遇到了2個問題。
@match
應該是每個translate.google.com搜索而不僅僅是胃口。 如何指定整個域? 你能幫我完成這個用戶嗎?
修改:似乎設置match
https://translate.google.com/
match
處理第一個問題。 仍然不知道為什么click()不起作用。
請參閱在AJAX驅動的站點上選擇並激活正確的控件 。
控件並不總是通過click
操作。 Google頁面尤其如此。
此按鈕有幾個您需要注意的事項:
#gt-pb-star > .trans-pb-button
, 而不是 #gt-pb-star
。 這是一個Greasemonkey / Tampermonkey腳本,可以完成所有這些:
// ==UserScript==
// @name _Auto click the Star button on Google Translate
// @match https://translate.google.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
waitForKeyElements ("#gt-pb-star > .trans-pb-button", clickNodeWhenVisible);
function clickNodeWhenVisible (jNode) {
if (jNode.is (":visible") ) {
triggerMouseEvent (jNode[0], "mouseover");
triggerMouseEvent (jNode[0], "mousedown");
triggerMouseEvent (jNode[0], "mouseup");
}
else {
return true;
}
}
function triggerMouseEvent (node, eventType) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent (eventType, true, true);
node.dispatchEvent (clickEvent);
}
根據Brock Adams的回答,這是我存儲搜索的完全智能代碼:
// ==UserScript==
// @name _Auto click the Star button on Google Translate
// @match https://translate.google.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
function triggerMouseEvent (node, eventType) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent (eventType, true, true);
node.dispatchEvent (clickEvent);
}
$(window).on('hashchange', function(e){
var firstURL = window.location.href;
console.log(firstURL);
setTimeout(function(){
var secondURL = window.location.href;
if (firstURL == secondURL){
var el = document.getElementById("gt-pb-star").firstChild;
if (el.classList.contains("trans-pb-button-saved")){
}else{
triggerMouseEvent (el, "mouseover");
triggerMouseEvent (el, "mousedown");
triggerMouseEvent (el, "mouseup");
}
}
},3000);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.