在Chrome扩展程序中使用谷歌图表

Using Google Charts in Chrome extension

本文关键字:谷歌 Chrome 扩展 程序      更新时间:2023-09-26

我想在我的扩展中使用图表库。谷歌图表库似乎是最方便的一个。但是我不能在注入页面的脚本中使用它。我的清单.json看起来像这样:

...
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"content_scripts": [
  {
    "js": ["loader.js", ...],
    ...
  }
],
...

但我总是收到这些错误:

jsapi_compiled_format_module.js:1 Uncaught ReferenceError: google is not defined
jsapi_compiled_default_module.js:1 Uncaught ReferenceError: google is not defined
jsapi_compiled_ui_module.js:1 Uncaught ReferenceError: google is not defined
jsapi_compiled_corechart_module.js:1 Uncaught ReferenceError: google is not defined

而且它只是脚本中的一行:

google.charts.load('current', {'packages':['corechart']});

那么有什么方法可以让它工作吗?

loader.js尝试通过在页面中插入<script>标记来添加其他代码。

由于内容脚本上下文

隔离,这些脚本在页面的上下文(而不是内容脚本上下文)中执行。因此,google在页面中定义,但不在脚本中定义。

目前尚不清楚这是否可以解决。

  • 根据服务条款,您不得绕过加载程序,API 可能会主动阻止您这样做。
  • 您也可以将使用图表的代码注入到页面中,但这首先会打开上下文隔离的问题。

找到一个替代库要容易得多,您可以简单地包含在扩展中,例如 Chart.js。