Document get element BY ID Chrome extension using TYPESCRIPT

Viewed 31

I'm making a Chrome extension using Angular / Typescript and I'm trying to get the document element by id from the tab that is active and insert a value. On JS is working fine but on TS I don't know how to do it, because "document.getelementbyId" is not working for "HTML ELEMENT"

So, I used this piece of code:

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 GET THE ELEMENT BY ID AND IS NOT WORKING
            (<HTMLInputElement>document.getElementById('email')).value = "VALUE";

        }
       
  
    }
  });

I hope you understand the question and can help me to do it

1 Answers

Chrome.tabs only works on background scripts in v2, or service worker in v3. They both can not access document in current page, you will need to use content scripts and message passing to achieve this,

I can see you want todo something when a tab has update

You can do this:

  • in 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 do something
            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;
}
})

And document.getElementId can indicate it's return type, so you really don't need to declare type of it.

Related