IT

Chrome 확장 프로그램 : 콘텐츠 스크립트에서 localStorage에 액세스

lottoking 2020. 6. 15. 08:05
반응형

Chrome 확장 프로그램 : 콘텐츠 스크립트에서 localStorage에 액세스


따라서 사용자가 특정 옵션을 정의하고 localStorage에 저장하는 옵션 페이지가 있습니다. options.html

이제 options.html페이지에 정의 된 옵션을 가져와야하는 컨텐츠 스크립트가 있지만 컨텐츠 스크립트에서 localStorage에 액세스하려고하면 옵션 페이지에서 값을 반환하지 않습니다.

컨텐츠 스크립트가 localStorage, 옵션 페이지 또는 백그라운드 페이지에서 값을 가져 오려면 어떻게해야합니까?


2016 업데이트 :

구글 크롬은 스토리지 API를 공개했다 : http://developer.chrome.com/extensions/storage.html

다른 Chrome API와 마찬가지로 사용하기가 쉽고 Chrome의 모든 페이지 컨텍스트에서 사용할 수 있습니다.

    // Save it using the Chrome extension storage API.
    chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
      console.log('Settings saved');
    });

    // Read it using the storage API
    chrome.storage.sync.get(['foo', 'bar'], function(items) {
      message('Settings retrieved', items);
    });

그것을 사용하려면 매니페스트에서 정의해야합니다.

    "permissions": [
      "storage"
    ],

"제거", "클리어", "getBytesInUse"메소드 및 변경된 스토리지 "onChanged"를 청취하는 이벤트 리스너가 있습니다.

기본 localStorage 사용 ( 2011 년 이전 응답 )

콘텐츠 스크립트는 확장 페이지가 아닌 웹 페이지의 컨텍스트에서 실행됩니다. 따라서 컨텐츠 스크립트에서 localStorage에 액세스하는 경우 확장 페이지 저장소가 아닌 해당 웹 페이지의 저장소가됩니다.

이제 콘텐츠 스크립트가 확장 프로그램 (옵션 페이지에서 설정 한 확장 프로그램)을 읽을 수있게하려면 확장 메시지 전달 을 사용해야합니다 .

가장 먼저 할 일은 콘텐츠 스크립트가 확장에 요청을 보내 데이터를 가져 오도록 지시하는 것이며 그 데이터는 확장 localStorage가 될 수 있습니다.

contentscript.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});

API를 사용하여 일반 localStorage 데이터를 컨텐츠 스크립트로 가져 오거나 전체 localStorage 배열을 가져올 수 있습니다.

문제 해결에 도움이 되었기를 바랍니다.

화려하고 일반적인 ...

contentscript.js

chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});

때로는 chrome.storage API 를 사용하는 것이 좋습니다 . localStorage보다 낫습니다.

  • 컨텐츠 스크립트와 확장간에 메시지를 전달할 필요없이 컨텐츠 스크립트의 정보를 저장합니다 .
  • 데이터 를 JSON으로 직렬화하지 않고 JavaScript 객체로 저장합니다 ( localStorage는 문자열 만 저장함 ).

다음은 chrome.storage 사용을 보여주는 간단한 코드입니다. 컨텐츠 스크립트는 방문한 페이지의 URL과 타임 스탬프를 가져 와서 저장하며, popup.js는 저장 영역에서 가져옵니다.

content_script.js

(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();

popup.js

(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();

"Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.

Remember to declare storage permission in manifest.json.

manifest.json

...
"permissions": [
    "storage"
 ],
...

Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.

One downside is that it is asynchronous.

https://developer.chrome.com/extensions/storage.html

참고URL : https://stackoverflow.com/questions/3937000/chrome-extension-accessing-localstorage-in-content-script

반응형