UFO ET IT

localStorage를 사용할 수 있는지 확인

ufoet 2020. 11. 23. 20:39
반응형

localStorage를 사용할 수 있는지 확인


확인하는 데 많은 질문이 localStorage있었지만 누군가 브라우저에서 수동으로 종료하면 어떻게됩니까? 확인하는 데 사용하는 코드는 다음과 같습니다.

localStorage.setItem('mod', 'mod');
if (localStorage.getItem('mod') != null){
    alert ("yes");
    localStorage.removeItem('mod');
}else{
    alert ("no");
}

간단한 기능과 작동합니다. 그러나 Chrome 설정으로 이동하여 "데이터 저장 안 함"옵션을 선택하면 (정확히 기억하지 못함)이 기능을 실행하려고하면 Uncaught Error: SecurityError: DOM Exception 18. 그렇다면 그 사람이 완전히 꺼 졌는지 확인하는 방법이 있습니까?

업데이트 : 이것은 내가 시도한 두 번째 기능이며 여전히 응답이 없습니다 (경고).

try {
 localStorage.setItem("name", "Hello World!");
} catch (e) {
 if (e == QUOTA_EXCEEDED_ERR) {
     alert('Quota exceeded!');
}
}

modernizr의 접근 방식을 사용하십시오 (내 함수 이름을 더 나은 것으로 변경하고 싶을 수도 있습니다).

function lsTest(){
    var test = 'test';
    try {
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
    } catch(e) {
        return false;
    }
}

if(lsTest() === true){
    // available
}else{
    // unavailable
}

다른 방법만큼 간결하지는 않지만 호환성을 극대화하도록 설계 되었기 때문입니다.

원본 소스 : https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js

작동 예 : http://jsfiddle.net/6sm54/2/


나는 localStorage그것에 의존하는 모든 작업 전에 정의되어 있는지 확인 합니다.

if (typeof localStorage !== 'undefined') {
    var x = localStorage.getItem('mod');
} else {
    // localStorage not defined
}

최신 정보:

기능이 있고 꺼져 있지 않은지 확인해야하는 경우 더 안전한 접근 방식을 사용해야합니다. 완벽하게 안전하려면 :

if (typeof localStorage !== 'undefined') {
    try {
        localStorage.setItem('feature_test', 'yes');
        if (localStorage.getItem('feature_test') === 'yes') {
            localStorage.removeItem('feature_test');
            // localStorage is enabled
        } else {
            // localStorage is disabled
        }
    } catch(e) {
        // localStorage is disabled
    }
} else {
    // localStorage is not available
}

기능 감지 로컬 저장소는 까다 롭습니다. 실제로 그것에 도달해야합니다. 그 이유는 Safari가 localStorage개인 모드에서 기능적 객체 를 제공하기로 선택 했지만 quotum이 0으로 설정되어 있기 때문 입니다. 즉, 모든 단순 기능 감지는 통과 localStorage.setItem되지만를 호출 하면 예외가 발생합니다.

Web Storage API의 Mozilla 개발자 네트워크 항목에는 로컬 저장소 감지 기능에 대한 전용 섹션이 있습니다 . 해당 페이지에서 권장하는 방법은 다음과 같습니다.

function storageAvailable(type) {
    try {
        var storage = window[type],
            x = '__storage_test__';
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch(e) {
        return false;
    }
}

사용 방법은 다음과 같습니다.

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

당신이 NPM을 사용하는 경우, 당신은 잡아 수있는 스토리지를 사용할 사용

npm install -S storage-available

그런 다음 다음과 같이 함수를 사용하십시오.

if (require('storage-available')('localStorage')) {
    // Yippee! We can use localStorage awesomeness
}

면책 조항 : MDN의 문서 섹션과 NPM 패키지는 모두 제가 작성했습니다.


MDN 은 스토리지 감지 기능을 업데이트 했습니다. 2018 년에는 더 안정적입니다.

function storageAvailable() {
    try {
        var storage = window['localStorage'],
            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 && storage.length !== 0;
    }
}

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 support localStorage, 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.

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


With this function you can check if localstorage is available or not, and you keep under control the possible exceptions.

function isLocalStorageAvailable() {

    try {
        var valueToStore = 'test';
        var mykey = 'key';
        localStorage.setItem(mykey, valueToStore);
        var recoveredValue = localStorage.getItem(mykey);
        localStorage.removeItem(mykey);

        return recoveredValue === valueToStore;
    } catch(e) {
        return false;
    }
}

Here is an easy check:

if(typeof localStorage === 'undefined'){


Modifying Joe's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...

Object.defineProperty(this, "ls", {
  get: function () { 
    var test = 'test';
    try {
      localStorage.setItem(test, test);
      localStorage.removeItem(test);
      return true;
    } catch(e) {
      return false;
    }
  }
});

Use this to check localStorage is set or not. Its help you to get status of Localstorage.

    if( window.localStorage.fullName !== undefined){

           //action
   }else{
          }

참고URL : https://stackoverflow.com/questions/16427636/check-if-localstorage-is-available

반응형