Reputation: 2419
I am writing a chrome extension in which I am trying to use the chrome.identity API. But my Chrome doesn't recognize identity.
On the following code in developer tools, I get an error saying "Cannot read property getAuthToken of undefined:
chrome.identity.getAuthToken({ 'interactive': false }, function(token) {
I tried typing in the console. chrome.extension works but chrome.identity is undefined.
My manifest.json has "identity" in permissions. I am on latest Chrome v38. Is there anything else required to enable the identity API?
Upvotes: 33
Views: 12942
Reputation: 580
You can access it in your content script, ie content.js by using the 'Messaging API" to send a message to your background.js and return it to the content.js.
content.js:
chrome.runtime.sendMessage({type: "getAuthToken"}, function(response) {
alert(response.token);
});
and in background.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type === "getAuthToken") {
chrome.identity.getAuthToken({interactive: true}, function(token) {
sendResponse({token: token});
});
return true;
}
});
and your manifest.json should at minimum have these properties:
{
...
"permissions": [
...
"identity",
...
],
...
"background": {
"service_worker": "background.js"
},
...
"content_scripts": [
...
{
"matches": ["https://example.com/*"],
"js": ["content.js"],
"match_origin_as_fallback": false
},
...
]
}
Now when you go to example.com, an alert should appear with the logged in users token, assuming your extension has already logged in the user.
Upvotes: 4
Reputation: 2419
The reason I was not able to use identity was because I was trying to access it from a content script. I switched to a background script and it works now! Thanks Rob!
PS! You also need to have "permissions": ["identity"]
set in your manifest.json
.
Upvotes: 61
Reputation: 25974
It may require providing a "key" value in your manifest as well (if you're trying to get it working locally and it's not working). You can either use the same key as the one you get when you upload your extension to the webstore or try packing an extension to generate a new one (though I couldn't get this second approach working myself).
Upvotes: 2