首页 > 解决方案 > 根据 cookie 值打开 iframe

问题描述

我正在尝试设置一段代码,以便 iframe 仅在 cookie 的内容时加载'cookie_consent_user_accepted' = true

我已经设法使用其他脚本而不是 iframe 来做到这一点,并且有点迷失从哪里开始使用 iframe。

标签: javascriptcookies

解决方案


程序:

  1. 检查cookie是否存在。由于 cookie 的名称和值是不变的,因此只需对其进行硬编码即可消除几行代码。

  2. 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();
}

附加eventListenerbutton

document.querySelector('.btn').addEventListener('click',acceptCookie);

并检查 cookie 在窗口加载时是否存在

checkCookie();

JSFiddle 支持 cookie,所以我在那里创建了一个小提琴。这是链接


推荐阅读