Muhammed Ozdogan
Muhammed Ozdogan

Reputation: 5867

How to use Chrome Extension Api with Angular?

I am working on a chrome extension, I have a "background.js" which it filters the url and fetchs data from my api. When the conditions is meet I am sending a message from "background.js". And I want to catch it from Angular component.

background.js

...
chrome.pageAction.show(tab.id, () => {
            chrome.runtime.sendMessage({data: dataFromAPI})
        });
...

I ran npm install --save @types/chrome.

app.component.ts

import {Component} from '@angular/core';
import {chrome} from '@types/chrome';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor() {
    chrome.runtime.onMessage.addListener( data => console.log(data));
  }

}

But WebStorm says, ".../node_modules/@types/chrome/index.d.ts' is not a module. "

How can I use Chrome Api from Angular Component?

Upvotes: 6

Views: 7075

Answers (3)

Saad Qamar
Saad Qamar

Reputation: 1099

In my case, I installed npm install --save @types/chrome

so file stop showing an error Cannot find name 'chrome' when build

then I'm trying to build the library by using the command ng build but it was broken because it didn't find a chrome so what I did?

I added this line ///<reference types="chrome"/> on top of file public-api.ts

Note: Must add three slashes(///) before reference.

Upvotes: 1

Anish Aralikatti
Anish Aralikatti

Reputation: 365

Add the line

///<reference types="chrome"/>

to the very top of your TS file (preferably line 1). (DO NOT OMIT THE 3 SLASHES IN THE BEGINNING)

Also run the command

npm install --save @types/chrome 

Things will start working after that.

Upvotes: 4

Gaurav Kumar
Gaurav Kumar

Reputation: 41

/// <reference types="chrome"/>
import {chrome} from '@types/chrome';
// Remove chrome import

IMPORTANT: Must add three slashes before reference.

If still it doesn't work then add "Chrome" in tsconfig.json types.

compilerOptions: ["types": [ "Chrome" ] ]

Upvotes: 4

Related Questions