Javascript 如何在浏览器 JS 控制台中包含脚本时覆盖内容安全策略?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27323631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:01:36  来源:igfitidea点击:

How to override content security policy while including script in browser JS console?

javascriptbrowser-extensioncontent-security-policybrowser-security

提问by Pranjal Mittal

I was trying to include JQuery on an existing website using console this way:

我试图以这种方式使用控制台在现有网站上包含 JQuery:

var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-1.11.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

Then I got this error:

然后我得到了这个错误:

Content Security Policy: The page's settings blocked the loading of a resource at http://code.jquery.com/jquery-1.11.1.min.js ..

During development I might want to include external Javascript. I might not want to copy paste the entire JQuery code since it does not look neat. How to override the content security policy for development purposes?

在开发过程中,我可能想要包含外部 Javascript。我可能不想复制粘贴整个 JQuery 代码,因为它看起来不整洁。出于开发目的,如何覆盖内容安全策略?

This would be really useful for quick testing. I might want to convert the script I am writing to a browser extension later on.

这对于快速测试非常有用。我可能想稍后将我正在编写的脚本转换为浏览器扩展。

Note(update): I am writing the script over an existing website and do not have control over setting the Content-Security-Policy header.

注意(更新):我正在现有网站上编写脚本,并且无法控制设置 Content-Security-Policy 标头。

回答by apsillers

You can turn off the CSP for your entire browser in Firefox by disabling security.csp.enablein the about:configmenu. If you do this, you should use an entirely separate browser for testing. For example, install Firefox Developer Editionalongside your normal browser and use that for testing (and notnormal Web use).

您可以通过security.csp.enableabout:config菜单中禁用来关闭 Firefox 中整个浏览器的 CSP 。如果你这样做,你应该使用一个完全独立的浏览器进行测试。例如,将Firefox Developer Edition与您的普通浏览器一起安装,并将其用于测试(而不是普通的 Web 使用)。

As an alternative, it should be possible to alter the Content-Security-Policyresponse header before it gets to your browser (via an HTTP proxy). It is also possible to do this with extensions.

作为替代方案,应该可以在Content-Security-Policy响应头到达您的浏览器之前对其进行更改(通过 HTTP 代理)。也可以通过扩展来做到这一点。

A Chrome extension can set its own CSPfor its own chrome-extension://...pages, but it cannot alter the CSP of a normal webpage.

Chrome 扩展程序可以为自己的chrome-extension://...页面设置自己的 CSP,但不能更改普通网页的 CSP。