DEV Community

J-Sandaruwan
J-Sandaruwan

Posted on • Edited on

Chrome extension with React (how to get the URL of the current tab)

Image cover

Before continue that project we need to follow early blog. 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


Enter fullscreen mode Exit fullscreen mode

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



"permissions": [
   "activeTab"
],


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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



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,
               }
           }
       },
   }
}


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

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.



"content_scripts": [
   {
       "matches": ["http://*/*", "https://*/*"],
       "js": ["./static/js/content.js"]
   }
],


Enter fullscreen mode Exit fullscreen mode

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,



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);


Enter fullscreen mode Exit fullscreen mode

04.Use that DOMEvaluator

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



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


Enter fullscreen mode Exit fullscreen mode

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

Thank you,
J-Sandaruwan.
linkedin

Top comments (3)

Collapse
 
thomasbnt profile image
Thomas Bnt

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
jsandaruwan profile image
J-Sandaruwan

Thank you. I will update code.

Collapse
 
bumho12 profile image
Bum-Ho12

I am trying to understand everything but it seems the files for DOMMessage and DOMMessageResponse are not in this article thus it is hard to comprehend what exactly is happening the ts file