简体   繁体   中英

does localStorage either or sessionStorage persist in open tab if data stored comes from within an iframe

If I load a iFrame into a child element of a tab the user is in, for use by the user as a means of selecting something from an external location, and I were to store that data from the selection using local or session storage methods would I be able to access that data once I close out the iFrame to continue on? Or even at all for that matter?

If not, is there still not a clean method of communicating child window to parent?

The following is a basic example of using localStorage between a parent window and an iFrame.

To demo, enter a value into the main page's textbox and click 'Set Data'. This will set the value in localStorage. Click 'Read Data' to output the value to the div.

Then enter another value in the iFrame's textbox, and click 'Set Data'.

Finally, click on 'Read Data' again and you will see the value set from the iFrame displayed in the main page's div.

main.html:

     <div id="divOne">
        <label>Enter a Value: </label><input id="txtOne" />
        <input type="button" id="btnOne" value="Set Data" onclick="btn1Click(this);" />
        <input type="button" id="btnTwo" value="Read Data" onclick="btn2Click(this);" />
    </div>
    <div id="divTwo"></div>
    <iframe id="ifOne" src="iframe.html"></iframe>

    <script type="text/javascript">
        var div2 = document.getElementById('divTwo');
        var btn1 = document.getElementById('btnOne');
        var btn2 = document.getElementById('btnTwo');
        var input1 = document.getElementById('txtOne');

        function btn1Click(e)
        {
            localStorage.dataItem = input1.value;
        }

        function btn2Click(e) {
            div2.innerHTML = localStorage.dataItem;
        }
    </script>

iframe.html:

    <div>
        <label>Enter a different Value: </label><input id="txtOne" />
        <input type="button" id="btnOne" value="Set Data" onclick="btn1Click(this);" />
    </div>

    <script type="text/javascript">
        var btn1 = document.getElementById('btnOne');
        var input1 = document.getElementById('txtOne');

        function btn1Click(e)
        {
            localStorage.dataItem = input1.value;
        }
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM