# get selected text in chrome

## EDIT

The method mentioned here is overcomplicated. To see a simple method, please refer to my answer at stackoverflow.com

## preface

I want to get the selected text in chrome. After hours of searching and trying, I finally figured it out. It’s not as simple as putting the javascript in a file and invoking the script.

## content.js

You need this file to inject your script into the target webpage. Without this file, it’s impossible to get the selected text.

Notice that if you want to get the HTML source code of the selected text, you can use the following content.js

## content.js to get the HTML source code instead of plain text

Here you can see, content.js sent a message including the selected text. So how we get the message? To achieve this, we need something called background page, which is running in the background. It’s usually called event.js

## event.js

event.js is not always running, but it will wake up when another view in the extension (for example, a popup) calls runtime.getBackgroundPage., just like the code in popup.js

You have to declare your background page (event.js) and relative permissions in manifest.json, the sample file is as follows:

## manifest.json

Finally, this is what popup.html looks like

You can find the demo source code here

This is the whole picture:

## Reference

Building a simple Google Chrome extension

Share