Utilize TypeScript in creating a Chrome extension to fetch elements by their ID

I'm currently working on a Chrome extension using Angular and Typescript, and I have encountered an issue with accessing the document element by its id from the active tab. While this works perfectly fine in JavaScript, I am facing difficulties in achieving the same functionality in TypeScript. It seems like "document.getelementbyId" does not work for HTML elements in TypeScript.

As a workaround, I have implemented the following code snippet:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
    if (changeInfo.status == 'complete' && tab.active) {
        if (tab.url == 'https://dashboard.stripe.com/login') {
            

            // THIS IS THE METHOD FOR GETTING THE ELEMENT BY ID, BUT IT'S NOT WORKING
            (<HTMLInputElement>document.getElementById('email')).value = "VALUE";

        }
       
  
    }
  });

If anyone can assist me in resolving this issue, I would greatly appreciate it. Thank you.

Answer №1

Chrome.tabs functionality is limited to background scripts in version 2, or service workers in version 3. Neither can directly access the document of the current page; instead, you will need to utilize content scripts and message passing for this purpose.

It appears that you want to perform a task when a tab updates. Here's how you can achieve it:

  • Within your service worker:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
    if (changeInfo.status == 'complete' && tab.active) {
        if (tab.url == 'https://dashboard.stripe.com/login') {
            // send message to content script to notify it to take action
            chrome.tabs.sendMessage(tab.id, {action: 'updateEmail', data:{emai: VALUE});
        }
    }
});

In your content script:

chrome.runtime.onMessage.addListener((req, sender, sendResponse)=>{
    if(req.action === 'updateEmail'){
        document.getElementById('email')).value = req.data.email;
    }
})

Also, note that document.getElementId inherently specifies its return type, so explicit declaration of its type is unnecessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incapable of acquiring the classification of the attribute belonging to the

Is it possible to retrieve the type of an object property if that object is stored in a table? const records = [{ prop1: 123, prop2: "fgdgfdg", }, { prop1: 6563, prop2: "dfhvcfgj", }] const getPropertyValues = <ROW extends o ...

Error: Trying to access a property of an undefined variable (retrieving 'x')

As a newcomer to the MEAN stack, I am attempting to create some basic posts. However, I keep encountering an error that reads TypeError: Cannot read properties of undefined (reading 'title') when trying to issue a post. The strange thing is, when ...

Exploring the traversal of an array of objects within Tree Node

How can I transform my data into a specific Tree Node format? Is there a method (using Typescript or jQuery) to iterate through each object and its nested children, grandchildren, and so on, and modify the structure? Current data format { "content" ...

Change the property value prior to running TypeScript validation

I possess the following object: const translations = { msg_hello: 'Hello', msg_bye: 'Bye' } In addition, I have a function that is structured as such: const generateTranslation = (partialKey: string): keyof typeof translations ...

Ways to retrieve information from forkJoin

Exploring rxjs for the first time and encountering an issue with forkJoin. In my Angular project, I have a service that combines data from two other services and then returns it to a component. However, when I call this service in my Angular component us ...

Is there any drawback in transforming Observables into promises?

There are situations where subscribing in a component is necessary instead of using an async pipe. In scenarios where only one value will be emitted by the observable, is there any drawback or downside to converting it to a promise? If we are not subscrib ...

"Design a function that generates a return type based on the input array

Created a function similar to this one // window.location.search = "?id1=123&id2=ABC&id3=456" const { id1, id2, id3 } = readArgsFromURL("id1", {name: "id2", required: false}, {name: "id3", required: true}) ...

In the en-US locale, the toLocaleDateString function is transforming "00:30" into 24:30

Questioning the Conversion of Time from 00:30 to 24:30 in en-US Locale options = { year: "numeric", day: "numeric", month: "numeric", hour: '2-digit', minute: '2-digit&apo ...

When using Angular and Express together, the session is not continuous as each new request generates a fresh session

Unique Question I have encountered an issue with passport.js while trying to implement authentication in my express application. When I use req.flash('message', 'message content') within a passport strategy, the flashed information see ...

Ensure the modal is closed when the user clicks on the Finish button within Docusign

I have a Docusign sign URL displayed in an iframe on my webpage. When the user clicks on FINISH, I want to close the modal iframe instead of redirecting to another page within the iframe. Please refer to the screenshot below for more clarity: I am implem ...

I am experiencing an issue with applying responsiveFontSize() to the new variants in Material UI Typography

I am looking to enhance the subtitles in MUI Typography by adding new variants using Typescript, as outlined in the documentation here. I have defined these new variants in a file named global.d.ts, alongside other customizations: // global.d.ts import * a ...

Multiple WAR files are nestled within an EAR file, facilitating the sharing of classes

Currently, my development setup involves Eclipse Neon and Maven. My projects consist of two main entities: Project 1 for all the Web services (SOAP and RESTful) and database access implementations, and Project 2 which houses the Angular implementation for ...

Mastering typing properties in React with TypeScript

Could someone please help me with this issue? I have created a basic react component. interface iRowData{ name: string } export default function ResultsSection(data: iRowData[]) { return <div>Results</div> } When I try to use it in ano ...

Click to load additional data until the list has reached its full length

<ng-container *ngFor="let item of itemList | slice:0:3"> <mat-checkbox>{{item}}</mat-checkbox> </ng-container> <div> <button id="loadMore">Load More</button> </div> I wo ...

Using TypeScript, Material UI introduces a new property to the primary object on the palette

Experimenting with the customization of MUI v5 theme has been a fun challenge in my current project. I have successfully tailored the theme to suit my requirements so far, but now I am faced with the task of adding a new property to the primary object defi ...

I encountered a problem while integrating antd and moment.js in my React project

I am currently using the antd date-picker in my React project with TypeScript. Encountered an error: Uncaught Type Error: moment is not a function. If anyone has a solution, please assist me. .tsx file:: const dateFormat = 'MM-DD-YYYY'; < ...

Is there a tool that can automatically arrange and resolve TypeScript dependencies, with or without the use of _references.ts file?

Currently, I am working on understanding the new workflow for "_references.ts" and I feel like there is something missing when it comes to using multiple files without external modules in order to produce correctly ordered ".js" code. To start with, I took ...

I am encountering an issue with an undefined variable called "stripe" in my Angular project, despite the fact

Within my stripecreditcardcomponent.html file: <script src="https://js.stripe.com/v3/"></script> <script type="text/javascript"> const payment = Stripe('removed secret key'); const formElements = paymen ...

What sets apart a JSON Key that is enclosed in double quotes "" from one that has no quotes?

Below is my TypeScript object: { first_name:"test", last_name: "test", birthdate:"2018-01-08T16:00:00.000Z", contactNumber: "12312312312", email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e19 ...

Accessing and manipulating a intricate JSON structure within an Ionic 3 framework to seamlessly connect it to the user

I'm currently developing an app using Ionic 3. Within my project, I have a JSON object structured like this: { "player": { "username": "thelegend", "platform": "xbox", "stats": { "normal": { "shots ...