【问题标题】:Is there any method to pass live data from one Browser tab another Browser tab by using Javascript是否有任何方法可以通过使用 Javascript 从一个浏览器选项卡另一个浏览器选项卡传递实时数据
【发布时间】:2021-06-28 05:10:45
【问题描述】:

我创建了一个递增和递减程序,但我想将数据从第一个浏览器传递到第二个浏览器(一个选项卡到另一个选项卡)。

在 Index.html 中有两个按钮用于递增和递减操作。在第二页上只有数据会显示,但我的代码只在同一个选项卡上工作。以及页面刷新后如何存储数据?

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="/index.js"></script>
    <link href="/index.css" rel="stylesheet" type="text/css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Users in Mall</title>
</head>
<body>
    <div class="container">
        <h1>Live Users in Mall</h1>
    <div class = "card">
        <button onclick = "decrement()">-</button>
        <h2 id = "root">0</h2>
        <button onclick = "increment()">+</button>
    </div>
    </div>
</body>
</html>

index.css

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
body{
    background-color: rgb(255, 255, 255);
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    text-align: center;
}
.card{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    padding: 100px;
}

h2{
    margin: 0 50px;
    font-size: 50px;
}
button{
    background-color: #ff9100;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    border-radius: 25px;
}
button:hover{
    background-color: rgb(206, 206, 206);
    color: #ff9100;
    border-color: #000 ;
}

index.js

var data = 0;
        document.getElementById("root").innerText = data;

        function decrement() {
            data = data-1;
            if (data <= 0)
            {
                data = 0;
            }

            document.getElementById("root").innerText = data;
            localStorage.setItem("key", data);
        }

        function increment() {
            data = data + 1;
            document.getElementById("root").innerText = data;
            localStorage.setItem("key", data);
        }

第二页名称为 Showdata

Showdata.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link href="/index.css" rel="stylesheet" type="text/css">
    <script src="/showdata.js"></script>

    <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>Show Live Data</title>
</head>
<body>
  
  <h3>Users Present in Mall</h3>
    <h2 id="root">0
</h2>  
</body>
</html>

showdata.js

var data = localStorage.getItem("key");
        document.write(data);       
       //output.innerHTML = data;
       //document.getElementById("root").innerText=data;

谁能为我的问题提供解决方案?

【问题讨论】:

  • 我对此知之甚少,无法写出完整的答案,但客户端存储是否是您正在寻找的?基本上使用两个选项卡都可以访问的客户端浏览器创建数据库?这是tutorial from Mozilla
  • broadcastChannel 似乎合适
  • 可能是SOCKET.IO

标签: javascript php html css web


【解决方案1】:

您可以使用的一种(几种)方法是使用BroadcastChannel api。 MDN 的简介:

BroadcastChannel 接口代表一个命名频道,任何 给定来源的浏览上下文可以订阅。它允许 不同文档之间的通信(在不同的窗口、标签、 相同来源的框架或 iframe)。消息通过一个广播 在侦听的所有 BroadcastChannel 对象上触发的消息事件 频道。

具有两个按钮的index 页面:

<!DOCTYPE html>
<html lang="en">
    <head>
        <style>
            * {
                padding: 0;
                margin: 0;
                box-sizing: border-box;
            }
            body{
                background-color: rgb(255, 255, 255);
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%,-50%);
                text-align: center;
            }
            .card{
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100%;
                padding: 100px;
            }

            h2{
                margin: 0 50px;
                font-size: 50px;
            }
            button{
                background-color: #ff9100;
                border: none;
                color: white;
                padding: 15px 32px;
                text-align: center;
                text-decoration: none;
                display: inline-block;
                font-size: 16px;
                margin: 4px 2px;
                cursor: pointer;
                border-radius: 25px;
            }
            button:hover{
                background-color: rgb(206, 206, 206);
                color: #ff9100;
                border-color: #000 ;
            }
        
        </style>
        
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Live Users in Mall</title>
    </head>
    <body>
        <div class="container">
            <h1>Live Users in Mall</h1>
            <div class="card">
                <!--
                    Rather than using `inline` function calls it is 
                    preferable to assign an external event listener.
                    You can easily use the same event handler to 
                    perform both increment and decrement tasks.
                    
                    To aid that the buttons were assign a dataset
                    attribute which is analysed in the click handler.
                -->
                <button data-action='decrement'>-</button>
                <h2>0</h2>
                <button data-action='increment'>+</button>
            </div>
        </div>
        <script>
        
            // Establish the communication channel - this can be (nearly) any name 
            // but the same name is needed for the listeners.
            
            let oChan=new BroadcastChannel( 'tabs' );
            let h2=document.querySelector('div.card h2');
            
            
            // simple function to send a payload of your design
            const sendmessage=function( data ){
                let payload={ 'data':data };
                oChan.postMessage( payload );
            };
    
    
            // fetch the data from localStorage or set as zero
            let data=localStorage.getItem('key');
            if( data == null )data=0;
            else data=Number( data );
            
            h2.innerHTML=data;
            
            
            // assign an event listener for both buttons
            document.querySelectorAll('button[data-action]').forEach( bttn=>{
                bttn.addEventListener('click',function(e){
                    switch( this.dataset.action ){
                        case 'increment':data++;break;
                        case 'decrement':data--;break;
                    }
                    
                    //update storage
                    localStorage.setItem('key',data);
                    
                    // send the message to the "other" page
                    sendmessage( data );
                    
                    // update local display
                    h2.innerHTML=data;
                });
            })
        </script>
    </body>
</html>

以及在点击按钮时实时更新的listening页面。

<!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>Show Live Data</title>
    </head>
    <body>
        <h3>Users Present in Mall</h3>
        <h2>0</h2>  
        <script>
            // establish listener on same channel
            let oChan=new BroadcastChannel( 'tabs' );
                oChan.addEventListener('message',(e)=>{
                    // process the messages as they arrive
                    document.querySelector('h2').innerHTML=e.data.data
                });
        </script>
    </body>
</html>

index 页面建立了一个监听器也必须订阅的频道,并发送一个简单的消息(数据类型非常灵活),该消息在第二个窗口/选项卡中处理

【讨论】:

  • 此代码在不同的选项卡中正常工作。非常感谢你,但是兄弟你能告诉我我可以使用这个代码从不同的浏览器标签访问数据吗??
  • 否 - 这不会跨浏览器工作。要允许跨浏览器通信,您需要一种不同的方法〜也许WebRTC
  • 兄弟其实我想在Admin和User端使用这段代码。在管理端第 1 页 index.html 页面出现,在用户端第 2 页 showdata.html 页面将出现。所以管理员和用户将使用不同的浏览器。那么你能告诉我如何将数据从一个浏览器传递到另一个浏览器吗?我想在大学项目中使用这个功能,而且截止日期快到了??。 Sooo请告诉我怎么做。
  • 你必须看看 webrtc - MDN - RTCDataChannel API
  • 兄弟,能否请您给我使用该函数(MDN-RTCDataChannel API)实现的代码(在上面的程序中)?
【解决方案2】:

您可以使用BrowserObject,并找到具有名称的窗口或选项卡,您可以附加到选项卡。

【讨论】:

  • 感谢您的贡献,欢迎来到 SO!在您的答案中包含一个功能代码示例,而不仅仅是文本描述,这是一个非常好的主意。就目前而言,您对 BrowserObject 的引用尚不清楚。实际上解释如何使用对象并找到它的名称等要好得多。 ?
猜你喜欢
  • 1970-01-01
  • 2014-02-18
  • 1970-01-01
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多