javascript - 根据 cookie 值打开 iframe
问题描述
我正在尝试设置一段代码,以便 iframe 仅在 cookie 的内容时加载'cookie_consent_user_accepted' = true
。
我已经设法使用其他脚本而不是 iframe 来做到这一点,并且有点迷失从哪里开始使用 iframe。
解决方案
程序:
检查cookie是否存在。由于 cookie 的名称和值是不变的,因此只需对其进行硬编码即可消除几行代码。
a) 如果是,隐藏Accept Cookie按钮,创建一个
iframe
并将其附加到容器中。
b) 如果没有,eventListener
则在按钮上添加一个并等待用户接受。用户接受后,转到2a。
代码:
注意:由于安全问题,Stacksnippet 不支持 cookie,所以我没有在此处使用该代码段
// A function to check whether the cookie exists or not
function checkCookie(){
// Checking if hardcoded cookie value exists in document.cookie
if(document.cookie.indexOf('cookie_consent_user_accepted=true')!=-1){
// If yes, remove message (along with the button and related stuff)
document.querySelector('.message').remove();
// Create iframe and append it to the container
var iframe = document.createElement('iframe');
iframe.src = "https://example.com";
document.querySelector('.container').append(iframe);
}
}
示例 HTML
<div class="container">
<div class="message">
Ok with cookies?
<button class="btn">Yes</button>
</div>
</div>
EventListener
为_button#click
function acceptCookie(){
document.cookie="cookie_consent_user_accepted = true";
checkCookie();
}
附加eventListener
到button
document.querySelector('.btn').addEventListener('click',acceptCookie);
并检查 cookie 在窗口加载时是否存在
checkCookie();
JSFiddle 支持 cookie,所以我在那里创建了一个小提琴。这是链接
推荐阅读
- python - 将循环理解转换为 numpy 形式
- django - Django 扩展 shell_plus 与 jupyter 实验室
- amazon-web-services - 阻止对给定国家/地区的所有 aws 资源的访问
- python - 在我的 Django 中为博客文章创建一个赞按钮?
- reactjs - 如何在反应原生中使用反应导航添加类似顶部选项卡的whatsapp
- c - 增量编码器 - 轮询或中断?
- asp.net-core - 学习.Net core 5 项目
- linux - Fedora 的 Gcc-multilib
- javascript - discord.js 的参数中的空格
- python - 具有重复值的 Pandas 数据透视表