Vaulstein
Vaulstein

Reputation: 22041

Insert selected value in extension page on Key press

I have created hot-keys using Google's commands options in the manifest.json file.

manifest.json:

"commands": {
    "name" : {
        "suggested_key": {
             "default": "Alt+N" 
        },
        "description": "Select name"
    },
    "lastname": {
        "suggested_key": {
            "default": "Alt+P"
        },
        "description": "Select Last name"
    }
}

I want to get selected text on press of hot-keys(E.g. name - Alt+N) and display it in the popup.html page.

I can get the selected text when I click on the extension with the below code:

chrome.tabs.executeScript( {
  code: "window.getSelection().toString();"
}, function(selection) {
  document.getElementById("product_name").value = selection[0];
});

And I can Insert the text in popup.html using:

chrome.commands.onCommand.addListener(function (command) {
    if (command === "name") {
         document.getElementById("name").value = SomeValue;
    } else if (command === "lastname") {
         document.getElementById("last_name").value = SomeValue;
     }
});

I tried using below code to make both work together:

popup.js:

chrome.commands.onCommand.addListener(function (command) {
    if (command === "name") {
         var SomeValue;
         SomeValue = window.getSelection().toString();
         document.getElementById("name").value = SomeValue;
    } else if (command === "lastname") {
         document.getElementById("last_name").value = SomeValue;
     }
});

But I get it as undefined. How can I achieve the required output?

Upvotes: 0

Views: 48

Answers (1)

woxxom
woxxom

Reputation: 73526

The popup page and its script exist only when the popup is shown so you can't add the listeners for browser-global hotkeys there.

Put chrome.commands.onCommand.addListener in a background or event page and use standard communication via chrome.runtime.sendMessage between the extension's pages.

Upvotes: 1

Related Questions