javascriptgoogle-chrome-extensionselectedtext

New tab with the url + selected text (js, Chrome extension)


I'm designer who tries to develop the chrome extension. Please don't guilt me that this question was answered. It wasn't. Here is what I want:

  1. User select text on any page on the web
  2. Clicks extension icon
  3. New tab opens with url: "http://music.yandex.ru/search?text=" + text_selected_at_step_1

This code obviously works

var seltext = "apparat";
chrome.tabs.create({ url: "http://music.yandex.ru/search?text=" + seltext });

My problem is that I can't put selected text into variable. This doesn't work:

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

var seltext = getSelectionText();

chrome.tabs.create({ url: "http://music.yandex.ru/search?text=" + seltext });

This also doesn't or I don't understand how to sum the result with my link

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

nor that

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSelection")
      sendResponse({data: window.getSelection().toString()});
    else
      sendResponse({}); // snub them.
});

I just want to assign a variable to the selected text. It looks like so obvious task, but it isn't. All frontend developers who I know yet have no solution.


Solution

  • Here's a minimal extension that opens new tabs based on the selected text, using the second method you listed to retrieve the currently selected text (tested in Chrome 68):

    manifest.json:

    {
        "manifest_version": 2,
        "version": "1.0",
        "name": "Yandex Searcher",
        "browser_action": {
        },
        "permissions": [
            "activeTab"
        ],
        "background": {
            "scripts": ["main.js"],
            "persistent": false
          }
    }
    

    main.js:

    chrome.browserAction.onClicked.addListener(function() {
        chrome.tabs.executeScript({
            code: "window.getSelection().toString(); "
        }, function(selection) {
            chrome.tabs.create({
                url: "http://music.yandex.ru/search?text=" + selection[0]
            });
        });
    });
    

    Demo:

    Here's a quick screen recording demonstrating the result.