How to get and set item by localstorage in iframe?

Member

by lottie , in category: HTML & CSS , 3 months ago

How to get and set item by localstorage in iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 3 months ago

@lottie 

To get and set an item by localStorage in an iframe, you can follow these steps:

  1. Get item by localStorage in iframe:
1
2
3
4
5
6
7
8
9
// Get the iframe element
var iframe = document.getElementById('myIframe');

// Access localStorage of the iframe's content window
var iframeStorage = iframe.contentWindow.localStorage;

// Get an item from localStorage
var value = iframeStorage.getItem('key');
console.log(value);


  1. Set item by localStorage in iframe:
1
2
3
4
5
6
7
8
// Get the iframe element
var iframe = document.getElementById('myIframe');

// Access localStorage of the iframe's content window
var iframeStorage = iframe.contentWindow.localStorage;

// Set an item to localStorage
iframeStorage.setItem('key', 'value');


Make sure to replace 'myIframe' with the ID of your iframe element. This code demonstrates how to access the localStorage of the iframe's content window and get/set items as needed.