javascript - 如何在没有内容安全策略错误的情况下在内容脚本中使用 Google +1?

标签 javascript google-chrome google-chrome-extension google-plus google-plus-one

我正在尝试构建使用 +1 google api 的 chrome 扩展程序.

我的 manifest.json 看起来像:

"manifest_version": 2,
"content_security_policy": "script-src 'self' https://apis.google.com; object-src 'self'",
...
"matches": ["http://demosite.com/*"],
"js": ["js/jquery.js","js/social/plusone.js"]    

如您所见,我已将 apis.google.com 列入白名单。

我的 plusone.js 看起来像:

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://apis.google.com/js/plusone.js";
head.appendChild(script);
    
$('li.subscription').before('<g:plusone></g:plusone>');

如您所见,我只是从白名单站点注入(inject)脚本标签。

不幸的是,当我加载页面时出现错误:

Refused to load the script apis.google.com//scs/apps-static//js/k=oz.gapi.ru.Fqrb4MMzOT8.O/m…sv=1/d=1/ed=1/am=IQ/rs=AItRSTNEKbnLkdtNZVz4hKH7VV4tY98scw/cb=gapi.loaded_0' because it violates the following Content Security Policy directive: "script-src 'self'".

这里所有类似的问题都说我应该使用 content_security_policy 将站点列入白名单,但正如您所见,我已经做到了。有什么问题吗?

最佳答案

扩展程序的 Content security policy 仅适用于扩展页面不适用于内容脚本
当您插入 <script>标记,它成为页面 CSP 的主题,因此更改 list 文件中的 CSP 字符串不会有任何影响。

为了解决这个问题,我建议加载scriptTagContext.js在您的其他内容脚本之前。先读README.md了解技术,然后从https://github.com/Rob--W/chrome-api/tree/master/scriptTagContext获取.

示例:每个 Github 页面上的 G+1

我以 Github 为例,因为它执行严格的内容安全策略。

list .json

{
    "name": "Google +1 on Github",
    "version": "1",
    "manifest_version": 2,
    "content_scripts": [{
        "js": [<strong>"scriptTagContext.js"</strong>, "contentscript.js"],
        "matches": ["*://*.github.com/*"]
    }],
    "permissions": [
        <strong>"*://apis.google.com/*"</strong>
    ]
}

scriptTagContext.js

https://raw.github.com/Rob--W/chrome-api/master/scriptTagContext/scriptTagContext.js获取

内容脚本.js

var script = document.createElement('script');
script.src = 'https://apis.google.com/js/plusone.js';
document.head.appendChild(script);

// Next snippet is equivalent to jQuery's $('body').prepend('<g:plusone/>')
document.body.insertAdjacentHTML('afterbegin', '<g:plusone></g:plusone>');

关于javascript - 如何在没有内容安全策略错误的情况下在内容脚本中使用 Google +1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21211060/

相关文章:

javascript - 在 ASP.NET MVC 中将值从下拉列表传递到数据库

javascript - 禁用 HTML 中表单的所有元素(提交按钮除外)?

google-chrome - Chrome Dev Tools 水平拆分

javascript - Chrome 扩展 NativeMessaging 'connectNative' 未定义

google-chrome-extension - 可选择注入(inject)内容脚本

javascript - 禁用 HTML5 弹出表单验证消息

javascript - Json 数组对象转字符串逻辑

javascript - 当匹配页面 url 时自动从 chrome 中删除缓存

javascript - 仅在 HTTP 中支持跨域请求 - 访问 Sencha Touch 示例

javascript - Google Chrome 扩展程序中的自动对焦