Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   localStorage и событие "storage" (https://javascript.ru/forum/events/55999-localstorage-i-sobytie-storage.html)

Decode 25.05.2015 00:45

localStorage и событие "storage"
 
Возможно ли сделать так, чтобы при изменении цвета фона у <body> в одной вкладке, цвет фона менялся бы и в другой? Цвет фона меняется при обновлении страницы.

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>localStorage</title>
	<style>
		html, body {
			height: 100%;
		}

		body {
			margin: 0;
			padding: 0;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.bg-1 {
			background: chocolate;
		}

		.bg-2 {
			background: aqua;
		}

		.bg-3 {
			background: grey;
		}

		h1 {
			color: white;
			font-size: 3em;
		}
	</style>
</head>
<body>
	<h1>Change the background color of the page when you reload.</h1>

	<script>
		var body = document.body,
			currentStyle = +localStorage.currentStyle || 0;

		window.addEventListener('load', function() {
			body.classList.add('bg-' + (currentStyle + 1));
			localStorage.currentStyle = ++currentStyle % 3;
		});

		window.addEventListener('storage', function( event ) {
			// body.classList.add('bg-' + +event.newValue);
			console.log(event.key);
		});
	</script>
</body>
</html>

Decode 25.05.2015 03:01

Заработало. Надо было локальный сервер запустить :D


Часовой пояс GMT +3, время: 07:07.