1

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.

1 Answers1

1

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.

Ollin Boer Bohan
  • 2,296
  • 1
  • 8
  • 12
  • why you removed your answer here: https://stackoverflow.com/questions/51776967/simple-rotating-hover-effect-wont-work/51777060#51777060. It's a correct and valid one – Temani Afif Aug 09 '18 at 23:49
  • yes but you provided another method ... my answer removed the translation but yours appended the rotation with translation ;) so they are different way to do – Temani Afif Aug 09 '18 at 23:59