How to use Chrome Extension Api with Angular?

|▌冷眼眸甩不掉的悲伤 提交于 2020-06-15 20:04:49

问题


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?


回答1:


/// <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" ] ]



回答2:


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.



来源:https://stackoverflow.com/questions/53169721/how-to-use-chrome-extension-api-with-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!