简体   繁体   中英

Save input fields Chrome extension

I need to create an extension that has two buttons: Copy and Paste. The Copy button will select the content of the text inputs and textareas on the page and save it in the storage module. The Paste button will paste the saved text on another page inside the inputs and textareas with the same ids.

I managed to do make it work using local sotrage, but it only saved the content on the same domain. I have tried to use the chrome.storage module to store and retrieve the data; I couldn't make it functional.

Can you please tell me what's the best approach for this issue?

Update: The extension works, but with a small inconvenience:

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {      
        storage.get('form_data', function(item) {
            sendResponse(item);
        });   
    }
});

This returns an error: Could not send response: The chrome.extension.onMessage listener must return true if you want to send a response after the listener returns.

var form_data;
chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {      
        storage.get('form_data', function(item) {
            form_data = item;
        });   
        sendResponse(form_data);
    }
});

This works, but I have to call the function twice (clicking the paste button), I'm guessing the first one returns undefined and gets the data afterwards and the second call returns the storage value.

I solved that issue with the following code:

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request['request_type'] === 'copy') {
      storage.clear();
      storage.set({'form_data' : request['form_data']});
    } else if (request['request_type'] === 'paste') {
        storage.get('form_data', function(item) {
          chrome.tabs.getSelected(null, function(tab) {
            chrome.tabs.sendMessage(tab.id, item['form_data']);
          });
        });
      }
});

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