keycloak~从login-status-iframe页面总结如何跨域传值

发布时间 2023-12-23 20:19:45作者: 张占岭

login-status-iframe.html是keycloak为我们提供的一种检测用户登录状态的页面,它要求用户对接的系统通过iframe进行嵌入,然后通过window.addEventListener去订阅子页面的信息。

提示: 所有 HTML DOM 事件,可以查看我们完整的https://www.runoob.com/jsref/dom-obj-event.html。

addEventListener说明

  • element.addEventListener(event, function, useCapture)
    • event(*必须):字符串,指定事件名,注意: 不要使用 “on” 前缀。 例如,使用 “click” ,而不是使用 “onclick”。
    • function(*必须):指定要事件触发时执行的函数。
    • useCapture(*可选):布尔值,指定事件是否在捕获或冒泡阶段执行。
      • true - 事件句柄在捕获阶段执行
      • false - 默认,事件句柄在冒

跨域传值的测试

主页面

<iframe src="http://localhost:7070/toLogin" id="you"></iframe>

<script>
  // 父页面向iframe页面发消息 ,子页面接到后,再向父页面发送消息
    var iframe = document.getElementById('you');
    iframe.onload = function () {
        // 向子页面发消息
        iframe.contentWindow.postMessage('Your message', 'http://localhost:7070');

        // 订阅从子页面发过来的消息
        window.addEventListener('message', function (event) {
            alert("主的" + event.origin);
            if (event.origin !== 'http://localhost:7070') {//这里的origin必须是子页面的域名,否则不会执行,因为这消息是子页面发过来的
                return;
            }
            console.log(event.data);
        });

    }
</script>

子页面

<script>
 <!-- 为了测试iframe与主页面之间传递数据添加的 -->
  window.addEventListener('message', function (event) {
      alert(event.origin);
      if (event.origin !== 'http://localhost:9090') { //http://localhost:9090是主页面的地址,说明消息是从主页面发过来的
          return;
      }
      // 处理从父页面发送过来的消息
      alert('Received message: ' + event.data);
      // 向主页面再发消息
      event.source.postMessage('Hello from iframe!', event.origin);
  }, false);
</script>

最后,你会从收到子页面的alert

再收到主页面的alert