Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6886261
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T05:44:13+00:00 2026-05-27T05:44:13+00:00

I’m writing a chrome application that injects js code to a page, when the

  • 0

I’m writing a chrome application that injects js code to a page, when the user selects any text a popup is shown next to the text.
I’m using the following code to receive the coordinates of the selected text:

    var rect = window.getSelection().getRangeAt(0).getBoundingClientRect();
    var bottom = rect.bottom + document.body.scrollTop;
    var left = rect.left + document.body.scrollLeft

it works great except for when the user selects some text inside an input area, when he does the bottom-left bounding rect coordinates are (0,0) and my popup is shown at the top left corner of the page.

Any ideas how to solve it? I need the solution to work only in chrome.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T05:44:14+00:00Added an answer on May 27, 2026 at 5:44 am

    The code below is an excact copy of the function at this answer. For an explanation of the code, have a look at the linked answer. Demo: http://jsfiddle.net/56Rep/5/

    // @author Rob W       https://stackoverflow.com/users/938089/rob-w
    // @name               getTextBoundingRect
    // @param input          Required HTMLElement with `value` attribute
    // @param selectionStart Optional number: Start offset. Default 0
    // @param selectionEnd   Optional number: End offset. Default selectionStart
    // @param debug          Optional boolean. If true, the created test layer
    //                         will not be removed.
    function getTextBoundingRect(input, selectionStart, selectionEnd, debug) {
        // Basic parameter validation
        if(!input || !('value' in input)) return input;
        if(typeof selectionStart == "string") selectionStart = parseFloat(selectionStart);
        if(typeof selectionStart != "number" || isNaN(selectionStart)) {
            selectionStart = 0;
        }
        if(selectionStart < 0) selectionStart = 0;
        else selectionStart = Math.min(input.value.length, selectionStart);
        if(typeof selectionEnd == "string") selectionEnd = parseFloat(selectionEnd);
        if(typeof selectionEnd != "number" || isNaN(selectionEnd) || selectionEnd < selectionStart) {
            selectionEnd = selectionStart;
        }
        if (selectionEnd < 0) selectionEnd = 0;
        else selectionEnd = Math.min(input.value.length, selectionEnd);
    
        // If available (thus IE), use the createTextRange method
        if (typeof input.createTextRange == "function") {
            var range = input.createTextRange();
            range.collapse(true);
            range.moveStart('character', selectionStart);
            range.moveEnd('character', selectionEnd - selectionStart);
            return range.getBoundingClientRect();
        }
        // createTextRange is not supported, create a fake text range
        var offset = getInputOffset(),
            topPos = offset.top,
            leftPos = offset.left,
            width = getInputCSS('width', true),
            height = getInputCSS('height', true);
    
            // Styles to simulate a node in an input field
        var cssDefaultStyles = "white-space:pre;padding:0;margin:0;",
            listOfModifiers = ['direction', 'font-family', 'font-size', 'font-size-adjust', 'font-variant', 'font-weight', 'font-style', 'letter-spacing', 'line-height', 'text-align', 'text-indent', 'text-transform', 'word-wrap', 'word-spacing'];
    
        topPos += getInputCSS('padding-top', true);
        topPos += getInputCSS('border-top-width', true);
        leftPos += getInputCSS('padding-left', true);
        leftPos += getInputCSS('border-left-width', true);
        leftPos += 1; //Seems to be necessary
    
        for (var i=0; i<listOfModifiers.length; i++) {
            var property = listOfModifiers[i];
            cssDefaultStyles += property + ':' + getInputCSS(property) +';';
        }
        // End of CSS variable checks
    
        var text = input.value,
            textLen = text.length,
            fakeClone = document.createElement("div");
        if(selectionStart > 0) appendPart(0, selectionStart);
        var fakeRange = appendPart(selectionStart, selectionEnd);
        if(textLen > selectionEnd) appendPart(selectionEnd, textLen);
    
        // Styles to inherit the font styles of the element
        fakeClone.style.cssText = cssDefaultStyles;
    
        // Styles to position the text node at the desired position
        fakeClone.style.position = "absolute";
        fakeClone.style.top = topPos + "px";
        fakeClone.style.left = leftPos + "px";
        fakeClone.style.width = width + "px";
        fakeClone.style.height = height + "px";
        document.body.appendChild(fakeClone);
        var returnValue = fakeRange.getBoundingClientRect(); //Get rect
    
        if (!debug) fakeClone.parentNode.removeChild(fakeClone); //Remove temp
        return returnValue;
    
        // Local functions for readability of the previous code
        function appendPart(start, end){
            var span = document.createElement("span");
            span.style.cssText = cssDefaultStyles; //Force styles to prevent unexpected results
            span.textContent = text.substring(start, end);
            fakeClone.appendChild(span);
            return span;
        }
        // Computing offset position
        function getInputOffset(){
            var body = document.body,
                win = document.defaultView,
                docElem = document.documentElement,
                box = document.createElement('div');
            box.style.paddingLeft = box.style.width = "1px";
            body.appendChild(box);
            var isBoxModel = box.offsetWidth == 2;
            body.removeChild(box);
            box = input.getBoundingClientRect();
            var clientTop  = docElem.clientTop  || body.clientTop  || 0,
                clientLeft = docElem.clientLeft || body.clientLeft || 0,
                scrollTop  = win.pageYOffset || isBoxModel && docElem.scrollTop  || body.scrollTop,
                scrollLeft = win.pageXOffset || isBoxModel && docElem.scrollLeft || body.scrollLeft;
            return {
                top : box.top  + scrollTop  - clientTop,
                left: box.left + scrollLeft - clientLeft};
        }
        function getInputCSS(prop, isnumber){
            var val = document.defaultView.getComputedStyle(input, null).getPropertyValue(prop);
            return isnumber ? parseFloat(val) : val;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.