Chrome extension with React (how to get the URL of the current tab)
Published: 2022-09-22 18:02:05


![Image cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ee52vdll5prmm1bjt5u0.png)

Before continue that project we need to follow early [blog](https://dev.to/jsandaruwan/chrome-extension-with-react-70p/). After the create a **Chrome extension with React* flow those steps.

## 1.set up for read Chrome API

In that step, we want to mainly install an Our React app's chrome object that accesses the Chrome API. Chrome.tabs.query may be used to directly query browser tabs. First, install that types.

```
yarn add @types/chrome
```

Our addon simply requires activeTab permission to access the current tab. Add a new permissions key to your manifest.json.

```js
"permissions": [
   "activeTab"
],
```

Content scripts are JavaScript files that run on web pages and are separate from React.

We learned that React generates just one code file when we discussed how CRA develops our code. How can we produce a React app file and a content script file?

We could change CRA build parameters to create two files. Craco helps with this.

To install Craco, 

```
yarn add  @craco/craco --save
```

After that we create craco.config.js in your project's root directory. This file overrides build settings.

```js
module.exports = {
   webpack: {
       configure: (webpackConfig, {env, paths}) => {
           return {
               ...webpackConfig,
               entry: {
                   main: [env === 'development' && require.resolve('react-dev-utils/webpackHotDevClient'),paths.appIndexJs].filter(Boolean),
                   content: './src/chromeServices/DOMEvaluator.ts',
               },
               output: {
                   ...webpackConfig.output,
                   filename: 'static/js/[name].js',
               },
               optimization: {
                   ...webpackConfig.optimization,
                   runtimeChunk: false,
               }
           }
       },
   }
}
```

Now we can update our package.json build section like this,

```
"build": "INLINE_RUNTIME_CHUNK=false craco build",
```

## 02. Chrome content scripts

We created a file named content.js as part of our build project, however, Chrome doesn't recognize it.

Configure our extension so the browser knows about this file and injects it as a content script. A manifest file is affected.

In the manifest, content scripts are specified. Each script must provide the file location and target URLs.

Now we will add the new section on the manifest.json file.

```js
"content_scripts": [
   {
       "matches": ["http://*/*", "https://*/*"],
       "js": ["./static/js/content.js"]
   }
],
```
Chrome injects content.js into HTTP and HTTPS websites with these parameters.

## 03. DOMEvaluator content script

We're ready with setups, libraries, and settings. Only our DOMEvaluator content script and messaging API are missing to accept requests and transmit information to React components.

Create the missing file. Create chromeServices and DOMEvaluator.ts in src like this,

```js
import { DOMMessage, DOMMessageResponse } from '../types';

const messagesFromReactAppListener = (
   msg: DOMMessage,
   sender: chrome.runtime.MessageSender,
   sendResponse: (response: DOMMessageResponse) => void) => {
  
   console.log('[content.js]. Message received', msg);
 
   const headlines = Array.from(document.getElementsByTagName<"h1">("h1"))
                       .map(h1 => h1.innerText);

   const response: DOMMessageResponse = {
       title: document.title,
       headlines
   };
 
   sendResponse(response);
}
 
chrome.runtime.onMessage.addListener(messagesFromReactAppListener);
```
## 04.Use that DOMEvaluator

With the tab reference, we may send a message to the site's content scripts.

```js
chrome.tabs.sendMessage(
   tabs[0].id || 0,
   { type: 'GET_DOM' } as DOMMessage,
response
   (response: DOMMessageResponse) => {
       console.log(response)
   });
```

That way to get the URL of the current tab from Chrome extension.

Thank you,
J-Sandaruwan.
[linkedin](https://www.linkedin.com/in/j-sandaruwan/)