Hiero
Hiero

Reputation: 2205

Chrome extension copy and paste

So I'm building a private chrome extension. I have popup.html with two buttons, one is copy and other is paste.

The logic is like this:

  1. Press copy button in popup, and copy some form data
  2. Go to other website and press paste and inject in other form

So I use chrome.extension.sendMessage to detect clicking on popup buttons and listen to messages chrome.extension.onMessage.addListener where I switch what action was fired an execute some script.

The things is that I can get the information, I know how to inject it but I dont know where to save it so I can use it in different tab.

Does anybody has some ideas?

function dispatch(action) {
    return function() {
        chrome.extension.sendMessage({directive: action}, function(response) {
            this.close();
        });
    }
}



document.addEventListener('DOMContentLoaded', function() {

    copy = document.getElementById('copy');
    paste = document.getElementById('paste');

    copy.addEventListener('click', dispatch('COPY'));
    paste.addEventListener('click', dispatch('PASTE'));
})

Upvotes: 2

Views: 1612

Answers (1)

rafaelcpalmeida
rafaelcpalmeida

Reputation: 874

You can use local storage to store the value you want, paste it and then delete it again.

You can store values in the local storage using:

chrome.storage.local.set({ 'KEY': 'VALUE' }, function(){});

And you can retrieve from storage using:

chrome.storage.local.get('KEY', function(items) {
    //use the retrieved data with items.KEY
});

And in the manifest.json you need to add the following line:

"permissions": ["storage"]

For instance, if the key I'm using is 'SNT', I set using:

chrome.storage.local.set({ 'SNT': 'VALUE' }, function(){});

And I retrieve it using:

chrome.storage.local.get('SNT', function(items) {
    $("#divID").text(items.SNT);
});

If you wan't to see a working example you can check this GitHub repository.

Upvotes: 3

Related Questions