Chrome.identity不可用/未定义。

30

我正在编写一个Chrome扩展程序,试图使用Chrome.identity API。但是我的Chrome浏览器无法识别identity。

在开发者工具中的以下代码中,我会收到一个错误,提示“Cannot read property getAuthToken of undefined”:

chrome.identity.getAuthToken({ 'interactive': false }, function(token) {

我尝试在控制台中输入。chrome.extension可以使用,但chrome.identity未定义。

我的manifest.json文件中有"identity"权限。我使用的是最新的Chrome v38版本。是否还需要其他内容才能启用身份验证API?


4
这个API不能在内容脚本中使用。 - Rob W
1
身份示例(https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/identity)在扩展中的js文件中使用它,就像我一样。我确定我漏掉了什么。 - Bonton255
12
该API可以在后台页面、扩展页面、选项页面或弹出页面中使用,但不能在内容脚本中使用。 - Rob W
1
谢谢,Rob。这就是我正在寻找的信息。真的很有帮助! - Bonton255
3个回答

54

我之前无法使用身份验证是因为我试图从内容脚本中访问它。我切换到后台脚本,现在可以使用了!谢谢 Rob!

PS!您还需要在manifest.json中设置"permissions": ["identity"]


5
我正在尝试在 background.js 中进行,但它没有起作用。 - Tahir Yasin
3
我花了几个小时在同一个问题上苦苦挣扎。令人惊讶的是,这个问题在文档中没有提到。 - arhoskins
17
我也遇到了这个问题,后来发现我忘记在manifest.json中添加"permissions":["identity"]了。 - adrianmcli
@adrianmc 这应该被包含在被接受的答案中!最有可能是罪犯 - Arthur
2
如何让content.js在background.js中调用getAuth函数? - gumuruh
显示剩余2条评论

2

您可以通过使用“消息传递API”将消息发送到您的background.js并将其返回到content.js,从而在您的内容脚本中访问它。

content.js:

chrome.runtime.sendMessage({type: "getAuthToken"}, function(response) {
  alert(response.token);
});

在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;
  }
});

而你的 manifest.json 至少应该具备以下属性:

{
  ...
  "permissions": [
    ...
    "identity",
    ...
  ],
  ...
  "background": {
    "service_worker": "background.js"
  },
  ...
  "content_scripts": [
    ...
    {
      "matches": ["https://example.com/*"],
      "js": ["content.js"],
      "match_origin_as_fallback": false
    },
    ...
  ]
}

现在当您访问example.com时,假设您的扩展程序已经登录了用户,一个警告框应该会出现,其中包含已登录用户的令牌。

2

如果您正在尝试在本地运行并且无法正常工作,可能需要在您的清单中提供“密钥”值。您可以使用与上传扩展名到网络商店时获得的相同密钥,或者尝试打包扩展以生成一个新密钥(尽管我自己无法使第二种方法工作)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接