Search code examples
javascriptbrowser-extension

How does the Google Translate extension make its icon image visible when text is highlighted?


I am trying to figure out how to make an icon image appear when text is selected like how the Google Translate extension does it. I've tried various combinations of "icon image appear", "text selected" and "Google Translate extension" on Google and SO and have had no luck. A general description (no code necessary!) of how Google Translate does it would go a long way because I don't think I am describing what I want to do in technical terms very well.

Icon appears when text is selected


Solution

  • This would need requirement-specific research and attempts to implement. Have you tried anything?

    I would approach checking/detecting is text selected through Javascript. In CSS we have the "::selection" property that indicates if a text is selected. Either look for this or with keyup, mouseup events set the "display" and "position" property of the Icon image.

    Google might have its own way of accomplishing these in its products, considering this as a requirement, I've given you an approach that I would take above.

    Having Google Translate extension installed in your browser, Inspect and check your developer tools -> Sources -> Content Scripts to explore the extension script.

    enter image description here

    Pretty-Print to see a readable code.