如果用戶未同意,則網站會在大約 1-2 秒后顯示 cookie 同意。這意味著,同意不是直接在源中,而是在 1-2 秒后在 dom 中。
我必須檢測用戶是否點擊了同意 div 內的按鈕。如果我使用檔案就緒功能,則不會檢測到單擊。我必須使用 setInterval 因為 setTimeout 不起作用。原因是必須在同意中打開另一個視窗,因此我不能像超時那樣使用固定時間。
Consent div 由類名稱為“cmp-consent”的 div 組成。我每 1800 毫秒用 setInterval 檢查該 div 的 dom。如果 1800 毫秒后 div 不存在,則用戶已經同意,我清除了 setInterval。
但:
如果 div 存在,它會一直等到用戶單擊同意標題中的第二個按鈕。當點擊時,再次點擊并關閉視窗。這作業得很好。
問題是,如果用戶沒有立即點擊這個按鈕(同意標題按鈕:eq (1)), setInterval 當然會繼續運行。可以看到console.log前面的計數器在增加。如果用戶隨后單擊該按鈕,則后續單擊的執行頻率與 setInverval 的頻率相同。如果用戶等待時間超過一分鐘,這將花費太長時間。問題是,你如何管理一個動作在 setInterval 中只執行一次。
這是我的腳本:
var userConsent = window.setInterval(function() {
if ($(".cmp-consent")[0]){
console.log('consent exists');
$( ".consent-header button:eq(1)" ).click(function(){
console.log('User clicked the button');
$(".primary button").click();
$(".close-icon").click();
window.clearInterval(userConsent);
});
} else {
console.log('consent given, remove interval');
window.clearInterval(userConsent);
}
}, 1800);
uj5u.com熱心網友回復:
這是@cloned 建議的一個作業示例。
document.addEventListener("click", function(e) {
for (var target=e.target; target && target!=this; target=target.parentNode) {
// loop parent nodes from the target to the delegation node
if (target.matches('.consent-header')) {
handler.call(target, e);
break;
}
}
}, false);
function handler() {
console.log('do stuff');
}
<div class="consent-header">
<button>I agree</button>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/391074.html
標籤:javascript 查询
