Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Last active May 6, 2022 18:48
Show Gist options
  • Save m3g4p0p/fe6e98aa5865718a90983f8f961214f6 to your computer and use it in GitHub Desktop.
Save m3g4p0p/fe6e98aa5865718a90983f8f961214f6 to your computer and use it in GitHub Desktop.
local storage communication
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<input id="message">
<script>
const message = document.getElementById('message')
message.addEventListener('input', () => {
localStorage.setItem('#test', message.value)
})
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<div id="test"></div>
<script>
window.addEventListener('storage', event => {
const target = document.querySelector(event.key)
if (target) {
target.textContent = event.newValue
}
})
</script>
</body>
</html>
@m3g4p0p
Copy link
Author

m3g4p0p commented May 6, 2022

Hi @febreno, thx! :)

Well using

document.getElementById('text')

won't work here since the #text element is not on the same document -- this was the very idea of using storage events for communication, so you'd set the textinput value to the local storage instead:

localStorage.setItem('#text', textinput)

... and the target page would have to listen to storage events as shown in the gist then.

Note that this will only work if both pages are on the same domain though.

Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment