Skip to content

[js] 第461天 sessionStrorage也可以使用onstorage事件吗? #2669

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第461天 sessionStrorage也可以使用onstorage事件吗?

3+1官网

我也要出题

Activity

Sun-Y0n9

Sun-Y0n9 commented on Jul 21, 2020

@Sun-Y0n9
  • 用以下代码测试, localStorage的变化可以监测到,sessionStorage的变化没有监测到.
  • 在浏览器两个标签打开文件, 其中一个点击设置, 查看另一个标签控制台的输出.
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<meta name="renderer" content="webkit">
	<title>Document</title>
	<style>
		button {
			width: 200px;
			height: 40px;
			border: none;
			background-color: aqua;
		}
	</style>
</head>
<body>
	<button id='local'>设置localStorage</button>
	<button id='session'>设置sessionStorage</button>
</body>
</html>
<script type="text/javascript">
	window.onstorage = function (e) {
		console.log(e.key + ' 键已经从 ' + e.oldValue + ' 改变为 ' + e.newValue + '.');
	};
	document.querySelector('#local').addEventListener('click', () => {
		localStorage.setItem('local', Math.random())
	});
	document.querySelector('#session').addEventListener('click', () => {
		sessionStorage.setItem('session', Math.random())
	});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@zhaofeipeter@Sun-Y0n9

        Issue actions

          [js] 第461天 sessionStrorage也可以使用onstorage事件吗? · Issue #2669 · haizlin/fe-interview