简体   繁体   English

保存输入字段Chrome扩展程序

[英]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. 粘贴按钮会将已保存的文本粘贴到输入和具有相同ID的文本区域内的另一页上。

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; 我尝试使用chrome.storage模块存储和检索数据; 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. 这将返回错误: 无法发送响应:如果要在侦听器返回后发送响应,则chrome.extension.onMessage侦听器必须返回true。

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']);
          });
        });
      }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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