Using chrome extension apis in typescript
JavascriptGoogle ChromeGoogle Chrome-ExtensionTypescriptWebstormJavascript Problem Overview
I'm building a chrome extension written in TypeScript. I'm using WebStorm and I added the chrome-DefiniteltyTyped
library in my project.
However, when I write this in my typescript code : chrome.extension.getURL
I got an error : cannot find name 'chrome'
.
Because of this, my javascript file is not generated and I cannot use it in my extension.
Do you guys have any solution?
Javascript Solutions
Solution 1 - Javascript
As of typescript 2 (or 2.x, not sure), you should import the chrome types from @types.
in package.json:
"devDependencies": {
...
"@types/chrome": "0.0.35", // or just npm install --save-dev @types/chrome
And in tsconfig:
"types": [
//(various types, e.g. jquery, core-js),
"chrome"
]
Solution 2 - Javascript
That should work fine : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/chrome/index.d.ts
TIP: make sure you have a reference
tag added:
/// <reference path="pathTo/chrome.d.ts"/>
Solution 3 - Javascript
Types Across Chrome and Firefox
Since the extension API is basically the same across Chrome and Firefox now, you can use @types/chrome
for both situations.
1. install
yarn add @types/chrome --dev
2. update tsconfig
{
"compilerOptions": {
....
"types": ["chrome"]
}
}
3. Get browser api function
export function getBrowserInstance(): typeof chrome {
// Get extension api Chrome or Firefox
const browserInstance = window.chrome || (window as any)['browser'];
return browserInstance;
}
Solution 4 - Javascript
You just need to install Type definition to make it work, let's install it:
yarn add @types/chrome --dev
or NPM
npm install @types/chrome --save-dev
now use free of error!
Solution 5 - Javascript
I just ran into the below error when trying to develop a Chrome extension using TypeScript in VS Code and all I had to do was simply run:
npm install --save-dev @types/chrome
This will enter "@types/chrome": "0.0.120" under "devDependencies" in your package.json file.
Fixed error:
[tsl] ERROR in C:\Users\my_user\Documents\my_chrome_extension\src\content.ts(28,3) TS2304: Cannot find name 'chrome'.
Solution 6 - Javascript
What did work:
Have typescript ignore the offending code by adding a comment like this above it.
// @ts-ignore: saying 'chrome' is not found
What didn't work:
- I had @types/chrome installed when I ran into this issue.
- In the tsconfig.json, adding "chrome" under types and specifying the typesroot.
- Adding a reference path comment and all sorts of ways to import "chrome".
try these before you add the @ts-ignore comment.
Background:
I am working on a chrome extension using Angular 11. I need to access chrome.runtime.sendMessage to send information to a background worker.