the thinking and solving of local storage problem

来源:互联网 发布:网络语言tnt是什么意思 编辑:程序博客网 时间:2024/05/21 18:40

this means ,you need:

1.get the value of volume which is now used.(how?)



2.storage them

3.read them and set them (initiate in app)


the solve of the problem,

two functions:

onunload 事件

onload 事件



js codes





//the storage of the setting information


    window.onload=function(){


        setStyles();
    };




    //when close the page 
    window.onunload=function(){


        populateStorage();
    
// if(!(localStorage.getItem('cvolume')&&localStorage.getItem('bgvolume')&&localStorage.getItem('brightness'))) {
//   populateStorage();
  
// } else {
//   setStyles();
// }
    // setStyles();


    };



    function setStyles() {
    var currentVolume1 = localStorage.getItem('cvolume');
     var currentVolume2 = localStorage.getItem('bgvolume');
    var currentBrightness= localStorage.getItem('brightness');

     document.getElementById('commentary-input').value = currentVolume1;
    document.getElementById('background-music-input').value = currentVolume2;
    document.getElementById('brightness-input').value = currentBrightness;
    }


    function populateStorage() {
    localStorage.setItem('cvolume', document.getElementById('commentary-input').value);
     localStorage.setItem('bgvolume', document.getElementById('background-music-input').value);
    localStorage.setItem('brightness', document.getElementById('brightness-input').value); 
    }

本文转之http://www.qqtimezone.top

在我们的日常生活中,时常遇到这么一种情况,当我们在点击一个链接、关闭页面、表单提交时等情况,会提示我们是否确认该操作等信息。

这里就给大家讲讲javascript的onbeforeunload()和onunload()两个事件。

相同点:

两者都是在对页面的关闭或刷新事件作个操作。

不同点:

  1. unbeforeunload()事件执行的顺序在onunload()事件之前发生。(因为,unbeforeunload()是在页面刷新之前触发的事件,而onubload()是在页面关闭之后才会触发的)。
  2. unbeforeunload()事件可以禁止onunload()事件的触发。
  3. onunload()事件是无法阻止页面关闭的。
  4. 浏览器的兼容
  • onunload:

  • IE6,IE7,IE8 中 刷新页面、关闭浏览器之后、页面跳转之后都会执行;

  • IE9 刷新页面 会执行,页面跳转、关闭浏览器不能执行;

  • firefox(包括firefox3.6) 关闭标签之后、页面跳转之后、刷新页面之后能执行,但关闭浏览器不能执行;

  • Safari 刷新页面、页面跳转之后会执行,但关闭浏览器不能执行;

  • Opera、Chrome 任何情况都不执行。

  • onbeforeunload:
  • IE、Chrome、Safari 完美支持

  • Firefox 不支持文字提醒信息

  • Opera 不支持

  • IE6,IE7会出现bug

  

示例代码:

onbeforeunload():

方式一:html元素中添加

复制代码
 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 </head> 7 <body onbeforeunload="return myFunction()"> 8  9 <p>该实例演示了如何向 body 元素添加 "onbeforeunload" 事件。</p>10 <p>关闭当前窗口,按下 F5 或点击以下链接触发 onbeforeunload 事件。</p>11 <a href="http://www.qqtimezone.top">博客地址</a>     12 <script>13 function myFunction() {14     return "自定义内容";15 }16 </script>17 18 </body>19 </html>
复制代码

方式二:javascript中添加

复制代码
 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>菜鸟教程(runoob.com)</title> 6 </head> 7 <body> 8  9 <p>该实例演示了如何使用 HTML DOM 向 body 元素添加 "onbeforeunload" 事件。</p>10 <p>关闭当前窗口,按下 F5 或点击以下链接触发 onbeforeunload 事件。</p>11 <a href="http://www.runoob.com">点击调整到菜鸟教程</a>12 <script>13 window.onbeforeunload = function(event) {14     event.returnValue = "我在这写点东西...";15 };16 </script>17 18 </body>19 </html>
复制代码

方式三:添加addEventListener()事件(不过此方法IE8以下不支持)

复制代码
 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 </head> 7 <body> 8  9 <p>该实例演示了如何使用 addEventListener() 方法向 body 元素添加 "onbeforeunload" 事件。</p>10 <p>关闭当前窗口,按下 F5 或点击以下链接触发 onbeforeunload 事件。</p>11 <a href="http://www.qqtimezone.top">跳转地址</a>12 <script>13 window.addEventListener("beforeunload", function(event) {14     event.returnValue = "我在这写点东西...";15 });16 </script>17 18 </body>19 </html>
复制代码

onunload():

方式一:html元素中添加

复制代码
 1 <!DOCTYPE html> 2 <html> 3 <head> 4     <title></title> 5     <script type="text/javascript"> 6         function fun() { 7             // dosomethings 8         } 9     </script>10 </head>11 <body onunload="fun()">12 13 </body>14 </html>
复制代码

方式二:javascript添加

复制代码
 1 <!DOCTYPE html> 2 <html> 3  4 <head> 5     <title></title> 6     <script type="text/javascript"> 7     window.onunload = function() { 8         // dosomethings 9     };10     </script>11 </head>12 13 <body>14 </body>15 16 </html>



https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API


The Web Storage API provides mechanisms by which browsers can securely store key/value pairs, in a much more intuitive fashion than using cookies. This article provides a walkthrough of how to make use of this simple technology.

Basic conceptsEdit

Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads.  The keys and the values are always strings (note that integer keys will be automatically converted to strings, just like what objects do). You can access these values like an object, or with the Storage.getItem() and Storage.setItem() methods.  These three lines all set the colorSetting entry in the same way:

localStorage.colorSetting = '#a4509b';localStorage['colorSetting'] = '#a4509b';localStorage.setItem('colorSetting', '#a4509b');

Note: It's recommended to use the Web Storage API (setItemgetItemremoveItemkeylength) to prevent the pitfalls associated with using plain objects as key-value stores.

The two mechanisms within Web Storage are as follows:

  • sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
  • localStorage does the same thing, but persists even when the browser is closed and reopened.

These mechanisms are available via the Window.sessionStorage and Window.localStorage properties (to be more precise, in supporting browsers the Window object implements the WindowLocalStorage and WindowSessionStorageobjects, which the localStorage and sessionStorage properties hang off) — invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorage and localStorage for each origin — they function and are controlled separately.

So, for example, initially calling localStorage on a document will return a Storage object; calling sessionStorage on a document will return a different Storage object. Both of these can be manipulated in the same way, but separately.

Feature-detecting localStorageEdit

To be able to use localStorage, we should first verify that it is supported and available in the current browsing session.

Testing for availability

Browsers that support localStorage will have a property on the window object named localStorage. However, for various reasons, just asserting that property exists may throw exceptions. If it does exist, that is still no guarantee that localStorage is actually available, as various browsers offer settings that disable localStorage. So a browser may supportlocalStorage, but not make it available to the scripts on the page. One example of that is Safari, which in Private Browsing mode gives us an empty localStorage object with a quota of zero, effectively making it unusable. However, we might still get a legitimate QuotaExceededError, which only means that we've used up all available storage space, but storage is actually available. Our feature detect should take these scenarios into account. 

Here is a function that detects whether localStorage is both supported and available:

function storageAvailable(type) {    try {        var storage = window[type],            x = '__storage_test__';        storage.setItem(x, x);        storage.removeItem(x);        return true;    }    catch(e) {        return e instanceof DOMException && (            // everything except Firefox            e.code === 22 ||            // Firefox            e.code === 1014 ||            // test name field too, because code might not be present            // everything except Firefox            e.name === 'QuotaExceededError' ||            // Firefox            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&            // acknowledge QuotaExceededError only if there's something already stored            storage.length !== 0;    }}

And here is how you would use it:

if (storageAvailable('localStorage')) {  // Yippee! We can use localStorage awesomeness}else {  // Too bad, no localStorage for us}

You can test for sessionStorage instead by calling storageAvailable('sessionStorage')

See here for a brief history of feature-detecting localStorage.

A simple exampleEdit

To illustrate some typical web storage usage, we have created a simple example, imaginatively called Web Storage Demo. The landing page provides controls that can be used to customize the color, font, and decorative image:

When you choose different options, the page is instantly updated; in addition, your choices are stored in localStorage,  so that when you leave the page and load it again later on, your choices are remembered.

We have also provided an event output page — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as a StorageEvent is fired.

Note: As well as viewing the example pages live using the above links, you can also check out the source code.

Testing whether your storage has been populatedEdit

To start with on main.js, we will test whether the storage object has already been populated (i.e., the page was previously accessed):

if(!localStorage.getItem('bgcolor')) {  populateStorage();} else {  setStyles();}

The Storage.getItem() method is used to get a data item from storage; in this case we are testing to see whether the bgcolor item exists; if not, we run populateStorage() to add the existing customization values to the storage. If there are already values there, we run setStyles() to update the page styling with the stored values.

Note: You could also use Storage.length to test whether the storage object is empty or not.

Getting values from storageEdit

As noted above, values can be retrieved from storage using Storage.getItem(). This takes the key of the data item as an argument, and returns the data value. For example:

function setStyles() {  var currentColor = localStorage.getItem('bgcolor');  var currentFont = localStorage.getItem('font');  var currentImage = localStorage.getItem('image');  document.getElementById('bgcolor').value = currentColor;  document.getElementById('font').value = currentFont;  document.getElementById('image').value = currentImage;  htmlElem.style.backgroundColor = '#' + currentColor;  pElem.style.fontFamily = currentFont;  imgElem.setAttribute('src', currentImage);}

Here, the first three lines grab the values from local storage. Next, we set the values displayed in the form elements to those values, so that they keep in sync when you reload the page. Finally, we update the styles/decorative image on the page, so your customization options come up again on reload.

Setting values in storageEdit

Storage.setItem() is used both to create new data items, and (if the data item already exists) update existing values. This takes two arguments — the key of the data item to create/modify, and the value to store in it.

function populateStorage() {  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);  localStorage.setItem('font', document.getElementById('font').value);  localStorage.setItem('image', document.getElementById('image').value);  setStyles();}

The populateStorage() function sets three items in local storage — the background color, font, and image path. It then runs the setStyles() function to update the page styles, etc.

We've also included an onchange handler on each form element, so that the data and styling is updated whenever a form value is changed:

bgcolorForm.onchange = populateStorage;fontForm.onchange = populateStorage;imageForm.onchange = populateStorage;

Responding to storage changes with the StorageEventEdit

The StorageEvent is fired whenever a change is made to the Storage object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects.

On the events page (see events.js) the only JavaScript is as follows:

window.addEventListener('storage', function(e) {    document.querySelector('.my-key').textContent = e.key;  document.querySelector('.my-old').textContent = e.oldValue;  document.querySelector('.my-new').textContent = e.newValue;  document.querySelector('.my-url').textContent = e.url;  document.querySelector('.my-storage').textContent = e.storageArea;});

Here we add an event listener to the window object that fires when the Storage object associated with the current origin is changed. As you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the new value after that change, the URL of the document that changed the storage, and the storage object itself.

Deleting data recordsEdit

Web Storage also provides a couple of simple methods to remove data. We don't use these in our demo, but they are very simple to add to your project:

  • Storage.removeItem() takes a single argument — the key of the data item you want to remove — and removes it from the storage object for that domain.
  • Storage.clear() takes no arguments, and simply empties the entire storage object for that domain.

SpecificationsEdit

SpecificationStatusCommentHTML Living StandardLiving Standard 

Browser compatibilityEdit

  • Desktop 
  • Mobile
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)localStorage43.5810.504sessionStorage52810.504

All browsers have varying capacity levels for both localStorage and sessionStorage. Here is a detailed rundown of all the storage capacities for various browsers.

Note: since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.

See alsoEdit

  • Web Storage API landing page


阅读全文
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 离开上海上海户口怎么办? 上海没房户口怎么办 没有房照动迁怎么办 持有上海居住证怎么办准生证 换公司后公积金怎么办 换工作了住房公积金怎么办 以前买的户口怎么办 上海落户积分不够怎么办 带坏受孕了怎么办 对公转账转错了怎么办 对公转错账怎么办 银行卡转错了怎么办 人户分离证明怎么办 暂居证怎么办才快 房产证户口本信息泄漏怎么办 户主迁走了户口怎么办 户口本丢了应该怎么办 户口本遗失了应该怎么办 户口迁出河南怎么办居住证 居住证学历写错怎么办 换单位了档案怎么办 辞职一年了档案怎么办 上海租房网签怎么办 户口本主页掉了怎么办 居转户办理中离职怎么办 上海居转户没有职称怎么办 上海居转户0税单怎么办 居转户出现零税怎么办 遇假记者敲诈怎么办 液氮挥发太快怎么办 高铁上空调太冷怎么办 文登市昆嵛酒店怎么办 厦漳泉同城包怎么办 亲戚朋友总是蹭吃蹭喝怎么办啊 开车上班总有蹭车的怎么办 食堂的饭难吃怎么办 租亲戚的房子怎么办 饭菜罩子生虫怎么办 食堂吃出虫子怎么办 缺氧没有煤炭了怎么办 缺氧没有金属了怎么办