简体   繁体   中英

How to use localStorage in chrome extension

I have created chrome extension which opens camera when click extension icon. my code in content.js works well. but when i reload site camera disappears. I know that if i want to show camera even reload page i have to use localStorage. But when i try to use it my camera doesn't work. can you help me please? can you show me how can i use localStorage for this case?

here is my code in content.js

chrome.runtime.onMessage.addListener(
    function({ShowCamera}, sender, sendResponse) {
        if(ShowCamera){
            let html = `
            <div class = "video-container">        
              <video style="width: 240px; margin: 0px;" autoplay="true" id="videoElement"></div>
            </div>`

            function setupCam() {
                 navigator.mediaDevices.getUserMedia({
                   video: true
                }).then(mediaStream => {
                    document.querySelector('#videoElement').srcObject = mediaStream;
                }).catch((error) => {
                  console.warn(error);
                });
              }

              setupCam();
              document.body.innerHTML += html;
            }   
 });

background.js

chrome.browserAction.onClicked.addListener(function(){
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {ShowCamera: "true"});    
  });
})
chrome.storage.local.set({ myKeyForCamAccess: 'myValueHere' });

chrome.storage.local.get('myKeyForCamAccess', (data) => {
        if (data.myKeyForCamAccess) {
          //do somthing
        }
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM