我制作了一个网站,其中嵌入了Google 可编程搜索引擎。但我希望它显示
<dialog>
在从 Google 加载脚本之前询问用户的同意。
为了不打扰回访者,应使用“记住我的同意”复选框来存储 cookie,以防止再次弹出对话框。
我想出了调整来自 Mozilla 的
dialog
演示来大致满足我的需求(➡️ jsfiddle)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<style>
dialog::backdrop {
backdrop-filter: blur(5px);
}
</style>
</head>
<body>
<dialog id="favDialog">
<form method="dialog">
<p><strong>If you proceed, Google will collect and process data according to the <a href="#">Google Privacy Policy</a>.</p>
<div>
<button value="disagreed">Cancel</button>
<button id="confirmBtn" value="agreed">I Agree</button><br />
<input type="checkbox" id="chkRemember" name="chkRemember" value="agreed-plus-cookies">
<label for="chkRemember">Remember my consent (this requires cookies, <a href="#">legal mumbo-jumbo</a> applies)</label>
</div>
</form>
</dialog>
<output></output>
<div class="gcse-searchresults-only" id="gcse_results"></div>
<script>
const gcse_results = document.getElementById('gcse_results');
const favDialog = document.getElementById('favDialog');
const outputBox = document.querySelector('output');
const confirmBtn = favDialog.querySelector('#confirmBtn');
const chkRemember = favDialog.querySelector('#chkRemember');
// automatically open the <dialog>
window.addEventListener("load", (event) => {
favDialog.showModal();
});
// checkbox sets value of the submit buttom
chkRemember.addEventListener('change', (e) => {
confirmBtn.value = chkRemember.value;
});
// "Confirm" button of form triggers "close" on dialog because of [method="dialog"]
favDialog.addEventListener('close', () => {
outputBox.value = `ReturnValue: ${favDialog.returnValue}.`;
});
</script>
<script async src="https://cse.google.com/cse.js?cx=c6dd01376f2fb45af"></script>
</body>
</html>
对话框返回 3 个可能的值:
disagreed
、agreed
、agreed-plus-cookie
我还不知道的是如何实际处理
${favDialog.returnValue}
,即:
<script async src="https://cse.google.com/cse.js?cx=mycode"></script>
Plain JS 受到高度赞赏。
这是我第二次尝试写这篇文章。对不起,我的第一次尝试很糟糕,我希望我做得更好——感谢那些指点我进行对话的人。事实证明,过去网络发生了很多事情。 :-)