简体   繁体   中英

Chrome Extension chrome.storage.local.set value is not passed from content script to Background Script

I am trying to pass the Input value from content script to background script and persist this value until changed in the extension.

However, the value is saved on the content script but it is not available in the background script.

Here is the Extension HTML:

<input type="text" class="InputControl form-control" id="Key"/>
<button class="save-to-key" id="saveButton" type="button">Save</button>

Here is content script that triggers based on the button click:

//use strict';
var KeyInput = document.getElementById("Key");
var SaveButton = document.getElementById("saveButton");


function SaveButtonclick() {      
    

    if(KeyInput.value!==""){
        chrome.storage.local.set({'key': KeyInput.value}, function() {

            chrome.runtime.sendMessage({messageType:"KeyData",Key:KeyInput.value});
            console.log(" click event value " + KeyInput.value);
            alert("Value currently is set by script  " + KeyInput.value);
            //window.close();

             if(chrome.runtime.lastError) {
               console.error(
                 "Error setting'key to " + JSON.stringify(KeyInput.value) +
                 ": " + chrome.runtime.lastError.message
               );
             }
           });

           chrome.storage.local.get("Key").then((result) => {
            console.log("extracted from storage" + result.Key);// this is undefined for some reason
              
          });
        }
    }
 //document.addEventListener('DOMContentLoaded', SaveButtonclick  , false);
 SaveButton.addEventListener('click',SaveButtonclick,false);

 chrome.runtime.onSuspend.addListener(() => {
    console.log("Unloading.");
});

Here is the background script:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if(message.messageType=="KeyData"){ 
        chrome.storage.local.set({"Key":message.key});
        console.log("Value currently is from message listeners "+message.key);
        sendResponse({'message':"KeyDataSavedSuccessfully"})
    }
});

chrome.runtime.onInstalled.addListener(function() {
    chrome.contextMenus.create({
        id: "1",
        title: "Save!",
        contexts:["selection"] // ContextType
       });
});



var KeyValue = function(word){
    var query = word.selectionText;
    var Key;
    chrome.storage.local.get("Key").then((result) => {
     Key=result.Key;
  });
  console.log("Value currently is  Main Script and get defaultvalues function is" + Key);
  chrome.tabs.create({url: "https://example.com/v1/test?sid="+query+"&Key="+Key+"&test=true"}); 
};

chrome.contextMenus.onClicked.addListener(KeyValue);

Hope you can help.

I noticed where i was going wrong. I am not waiting for the result so the value is undefined.

I changed the extension script here:

    //use strict';
    var KeyInput = document.getElementById("Key");
    var SaveButton = document.getElementById("saveButton");
    
    
    function SaveButtonclick() {      
        
    
        if(KeyInput.value!==""){
            chrome.storage.local.set({'key': KeyInput.value}, function() {
    
                
chrome.runtime.sendMessage({messageType:"KeyData",Key:KeyInput.value},function (response) {
                console.log("message sent to backgroud "+JSON.stringify(response));
                 
            });
                console.log(" click event value " + KeyInput.value);
                alert("Value currently is set by script  " + KeyInput.value);
                //window.close();
    
                 if(chrome.runtime.lastError) {
                   console.error(
                     "Error setting key to " + JSON.stringify(KeyInput.value) +
                     ": " + chrome.runtime.lastError.message
                   );
                 }
               });
    
               chrome.storage.local.get("Key").then((result) => {
                console.log("extracted from storage" + result.Key);// this is undefined for some reason
                  
              });
            }
        }
     //document.addEventListener('DOMContentLoaded', SaveButtonclick  , false);
     SaveButton.addEventListener('click',SaveButtonclick,false);
    
     chrome.runtime.onSuspend.addListener(() => {
        console.log("Unloading.");
    });

I changed this part in the background Script:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
        if(message.messageType=="KeyData"){ 
var Keyvaluetosave=message.Key;
            chrome.storage.local.set({"Key":Keyvaluetosave});
            console.log("Value currently is from message listeners "+Keyvaluetosave);
            sendResponse({'message':"KeyDataSavedSuccessfully"})
        }
    });
    
    chrome.runtime.onInstalled.addListener(function() {
        chrome.contextMenus.create({
            id: "1",
            title: "Save!",
            contexts:["selection"] // ContextType
           });
    });
    
    
        var KeyValue = function(word){
            var query = word.selectionText;
            var Key;
            chrome.storage.local.get("Key").then((result) => {
             Key=result.Key;
             console.log("Value currently is  Main Script and get defaultvalues function is" + Key);
             chrome.tabs.create({url: "https://example.com/v1/test?sid="+query+"&Key="+Key+"&test=true"});  
          });
          
        };

I did type in some part here on the... but this does fix the issue.. value is passed. If any one can improve this then please do so. Thank you so much...!

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