温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

html5中怎么实现前端跨域与监听效果

发布时间:2022-02-22 15:34:56 来源:亿速云 阅读:128 作者:iii 栏目:开发技术

这篇“html5中怎么实现前端跨域与监听效果”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“html5中怎么实现前端跨域与监听效果”文章吧。

第一步、架设两个不同端口的服务

我们这里用koa2来搭建两个服务到不同的端口,来模拟一下真正的工作中需要出现的跨域情况。

非常的简单 主要用到 koa-static这个中间件
搭建起来也是非常容易的,这里就不多说废话了 直接上代码 视频内会有详细的搭建步骤

// localhost:4000
const Koa = require('koa');
const path = require('path')
const static = require('koa-static')
const app = new Koa();
//设置静态资源的路径 
const staticPath = './static'
app.use(static(
    path.join( __dirname,  staticPath)
  )) 
console.log("服务启动在4000端口")
app.listen(4000);
// localhost:3000
const Koa = require('koa');
const path = require('path')
const static = require('koa-static')
const app = new Koa();
//设置静态资源的路径 
const staticPath = './static'
app.use(static(
    path.join( __dirname,  staticPath)
  ))
console.log("服务启动在4000端口")
app.listen(4000);

第二步、跨域通讯postMessage

我们首先来看一下 postMessageAPI

otherWindow.postMessage(message, targetOrigin, [transfer]);

otherWindow
其他窗口的一个引用,比如iframecontentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。

message
将要发送到其他 window的数据。它将会被结构化克隆算法序列化。这意味着你可以不受什么限制的将数据对象安全的传送给目标窗口而无需自己序列化。[1]

targetOrigin
通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符串""(表示无限制)或者一个URI。在发送消息的时候,如果目标窗口的协议、主机地址或端口这三者的任意一项不匹配targetOrigin提供的值,那么消息就不会被发送;只有三者完全匹配,消息才会被发送。这个机制用来控制消息可以发送到哪些窗口;例如,当用postMessage传送密码时,这个参数就显得尤为重要,必须保证它的值与这条包含密码的信息的预期接受者的origin属性完全一致,来防止密码被恶意的第三方截获。如果你明确的知道消息应该发送到哪个窗口,那么请始终提供一个有确切值的targetOrigin,而不是。不提供确切的目标将导致数据泄露到任何对数据感兴趣的恶意站点。

transfer 可选
是一串和message 同时传递的 Transferable 对象. 这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。

怎么样是不是很容易理解,这里给大家中文化一下。

要传输的那个(父)子窗口.postMessage(传输的内容, 传输到哪个地址, [权限是否转移(一般不用)]);

提前说一下,要想跨域传输,必须是父子页面,也就是说,是通过js Open的页面,或者ifream嵌套的页面

好了 我们开始来写代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
        <!-- postMessage和iframe解决普通的跨域问题 -->
    我是端口3000网站的内容
    <button onclick="send()">发消息给儿子</button>
    
    <iframe  src="http://localhost:4000" frameborder="0"></iframe>
<script>
        function send() { 
                window.frames[0].postMessage({a:"1"},"http://localhost:4000"); // 触发跨域子页面的messag事件
        }

    window.addEventListener('message', function(event) {
        console.info('儿子来信了', event);
    }, false);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
        <!-- postMessage和iframe解决普通的跨域问题 -->
    我是端口4000网站的内容
    <button onclick="send()">发消息给爸爸</button>
    
    <iframe  src="http://localhost:4000" frameborder="0"></iframe>
<script>
       window.addEventListener("message",function(event){
           console.log("爸爸来信了:", event)
        },false)

      function send() {
        parent.postMessage({a:1}, 'http://localhost:3000'); // 
     }
</script>
</body>
</html>

写到这里我们已经实现了父子页面的跨域通讯,但是这个通讯只发生在一个窗口内啊,并没有达到我想要的效果,该怎么办呢。

监听数值变化,做出及时反应

到这里大家需要思考,什么东西是浏览器上的所有同域名网站都能看到的呢?

没错,storage,我们只需要对这个进行监听就好了。

这里我们选择监听 loacalStorage 现在我们对子页面做一下改进

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
        <!-- postMessage和iframe解决普通的跨域问题 -->
    我是端口4000网站的内容
    <button onclick="send()">发消息给爸爸</button>
    
    <iframe  src="http://localhost:4000" frameborder="0"></iframe>
<script>
    
       window.addEventListener("message",function(event){
           console.log("爸爸来信了:", event)
           var data = JSON.stringify(event.data)
           window.localStorage.setItem("data",data)
        },false)

        window.onstorage(function(st){
            console.log(st.key,st.value)
        })
      function send() {
        parent.postMessage({a:1}, 'http://localhost:3000'); // 
     }

</script>

</body>
</html>

以上就是关于“html5中怎么实现前端跨域与监听效果”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI