5

I'm trying to determine the position of a selected text in my browser. I need the position to show a tooltip above the selected text. I guess if I get the boundaries, I'm able to calculate the middle of that. I fiddled around and looked here for suggestions, but couldn't find a solution.

If I'm not mistaken, this seems to be a problem related to Google Chrome?

Please be aware, that I'm trying to create a chrome-extension, so there is no need of testing if it works in Firefox / IE ...

This is all the code which causes the trouble:

var selection = window.getSelection();

// calculate the posiition of the selection
var oRange = selection.getRangeAt(0);
var oRect = oRange.getBoundingClientRect();
console.log(oRect);

(I tried to refer to this example here)

The error is like this:

background.js:20 Uncaught DOMException: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index.

If this is doable with jQuery, I don't mind using this as well, I'm not restricted to native JavaScript.

Complete code of my background.js

chrome.contextMenus.create({
    "title": "Übersetzen",
    "contexts": ["selection"],
    "onclick" : clickHandler
});

function clickHandler(e) {

    var translateUrl = "https://glosbe.com/gapi/translate?from=eng&dest=deu&format=json&phrase=" + encodeURI(e.selectionText.toLowerCase()) + "&pretty=true";
    $.getJSON(translateUrl, callback);
    // console.log(data.responseTex);
}

function callback(data) {
    var translation = data.tuc[0].phrase.text;
    var selection = document.getSelection();

     console.log(selection);


    // calculate the position of the selection
    var oRange = selection.getRangeAt(0);
    var oRect = oRange.getBoundingClientRect();
    console.log(oRect);
    var selection = "";

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        chrome.tabs.sendMessage(tabs[0].id, {translation: translation}, function(response) {});
    });
}

Update: When I run this code directly in the browser-console, it works as expected (If that is useful as a hint)

Update2: Maybe this is important: After selecting the text, I open the context-menu (via mouseclick) and click on an item, but the selection shouldn't be affected by this.

Update3: The code above works fine in an example-HTML page. My Background script seems to get an unfilled object (where there all the values are null)

Update 4: I added the complete code for reference (I also tried chrome.tabs.executeScript - but without success)

DasSaffe
  • 2,080
  • 1
  • 28
  • 67

1 Answers1

3

You need to get the selection in your content-script, not in the background script. Try calling your "onMessage"-method and use var s = window.getSelection() there. If you log this into the console, it works as expected.