Chrome扩展chrome.storage.local.set值未从内容脚本传递到后台脚本

7xllpg7q  于 2023-01-06  发布在  Go
关注(0)|答案(1)|浏览(184)

我试图将输入值从内容脚本传递到后台脚本,并保持该值,直到在扩展中更改。
但是,该值保存在内容脚本中,但在后台脚本中不可用。
下面是扩展HTML:

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

以下是根据按钮点击触发的内容脚本:

//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.");
});

下面是背景脚本:

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);

希望你能帮忙。

hujrc8aj

hujrc8aj1#

我注意到我哪里出错了!我没有等待结果,所以值是未定义的。
我在这里修改了扩展脚本:

//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.");
    });

我在后台脚本中更改了此部分:

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"});  
          });
          
        };

我确实在这里输入了一些部分...但这确实解决了这个问题...值被传递了。如果任何人可以改进这个,那么请这样做。非常感谢...!

相关问题