4

I have a gulp task that runs browsersync.

var options = {
        proxy :          'localhost:9000/html' ,
        port :           3000 ,
        files :          [
            config.root + config.srcPaths.htmlBundle ,
            config.htmlRoot + 'main.css' ,
            '!' + config.htmlRoot + '**/*.scss'
        ] ,
        injectChanges :  false ,
        logFileChanges : true ,
        logPrefix :      'broserSync ->' ,
        notify :         true ,
        reloadDelay :    1000
    };
browserSync( options );

browsersync detects changes and tries to inject them but chrome blocks it with this error:

Refused to connect to 'ws://localhost:3000/browser-sync/socket.io/?EIO=3&transport=websocket&sid=gOQQPSAc3RBJD2onAAAA' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

Uncaught SecurityError: Failed to construct 'WebSocket': Refused to connect to 'ws://localhost:3000/browser-sync/socket.io/?EIO=3&transport=websocket&sid=gOQQPSAc3RBJD2onAAAA' because it violates the document's Content Security Policy.

How can i overcome this issue? Can i turn off the security policy?

4

3 回答 3

7

Or you can add rules to your content security policy in the main html file (ex. index.html) to accept web socket connections from browser-sync. You can do it by adding ws://localhost:* to your default-src, for example like that:

<meta http-equiv="Content-Security-Policy"
      content="
        default-src 'self' ws://localhost:*">

You can also specify the exact browser-sync port like that:

<meta http-equiv="Content-Security-Policy"
      content="
        default-src 'self' ws://localhost:3000">

Just remember to remove this from policy before publishing to production servers!!

于 2015-07-29T09:38:26.483 回答
5

不确定这是否是最好的解决方案,但我最终做的是安装一个禁用 csp 的 chrome 插件:

https://chrome.google.com/webstore/detail/disable-content-security/ieelmcmcagommplceebfedjlakkhpden

如果有人有更好的解决方案,我会很高兴听到它。

于 2015-05-14T11:51:15.860 回答
3

如果在 html 元标记中设置了 CSP,那么一个稍微不那么难看的解决方案是让浏览器同步自行禁用它。在浏览器同步配置中添加这样的东西应该可以解决问题:

rewriteRules: [
  {
      match: /Content-Security-Policy/,
      fn: function (match) {
          return "DISABLED-Content-Security-Policy";
      }
  }
],

如果你真的很聪明,你可以注入正确的 CSP 规则,允许浏览器同步完成它的工作。也许一个勤奋的人最终会写一个插件来做到这一点?

于 2015-08-10T06:44:04.890 回答