获取 iframe 中的本地存储项

hak*_*ata 0 html javascript jquery local-storage

我有一个index.html包含一个 iframe 集的文件,并且 iframe 源指向另一个域。我正在设置 localstorageindex.html并尝试获取 iframe 源中的值。( sample.html)

File 1
index.html
    <html>
    <head>
    //js file 
    </head>
    <body>
    setting localstorage
    Iframe src="55.10.45.045/sample.html"
    </body>
    </html>

file 2
sample.html
       <html>
        <head>
        //js file 
        </head>
        <body>
        getting localstorage Item //Returns null
        </body>
        </html
Run Code Online (Sandbox Code Playgroud)

Bra*_*nek 5

你想使用这样的东西。

发送信息:

  window.onload = function() {
      var win = document.getElementById('iFrameId').contentWindow;

      win.postMessage(JSON.stringify({

          key: 'dataKey',
          data: dataPassing

      }), "*");

  };
Run Code Online (Sandbox Code Playgroud)

接收信息:

window.onmessage = function(e) {

     var payload = JSON.parse(e.data);
     localStorage.setItem(payload.key, payload.data);

};
Run Code Online (Sandbox Code Playgroud)

这会将 JSON 对象传递到 iFrame 中,然后框架中的脚本将获取它并将其推送到本地存储中。