js推送网页到扩展屏上--谷歌浏览器

 

平时我们推送网页、打开窗口都是用的 window.open,但是谷歌却不支持这种方法,也不是不支持,是可以打开窗口,但是无法将窗口移动到扩展屏上。

 

后面经过百度,发现了一个支持谷歌推送网页到扩展屏的方法:PresentationRequest

 

完整demo:

亲测有效

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>谷歌推送网页</title>
</head>
<body>
    <button onclick="test1()">推送</button>
    <!-- <button onclick="test2()">重连</button> -->
    <!-- <button onclick="test3()">关闭连接</button> -->
    <button onclick="test4()">关闭弹窗</button>
    <script>
        // document: https://w3c.github.io/presentation-api/
        var request = new PresentationRequest("https://baidu.com");
        navigator.presentation.defaultRequest = request;
        let con;
        var pId;

        function test1(){
            request.start().then(connect=>{
                console.log(connect.url)
                console.log(connect.id)
                pId = connect.id
            }).catch(err=>{console.log(err)});
        }

        // 监测连接是否可用
        request.addEventListener("connectionavailable", function(e){
            con = e.connection;
            con.addEventListener("close", function(){console.log("closed");})
            con.addEventListener("terminate", function(){console.log("terminated");})
            con.addEventListener("message", function(e){console.log(e.data);})
        })

        function test2(){
            request.reconnect(pId)
        }

        function test3(){
            con.close()
        }

        function test4(){
            con.terminate()
        }
    </script>
</body>
</html>

 

posted @ 2022-05-05 19:58  十一的杂文录  阅读(549)  评论(0编辑  收藏  举报