问题
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?
回答1:
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!!
回答2:
Not sure if it's the best solution, but what i ended up doing is to install a chrome plugin that disables the csp:
https://chrome.google.com/webstore/detail/disable-content-security/ieelmcmcagommplceebfedjlakkhpden
If anyone has a better solution i'll be glad to hear it.
回答3:
If the CSP is set in the html meta tag then a slightly less ugly solution is to have browser-sync disable this itself. Adding something like this to the browser-sync config should do the trick:
rewriteRules: [
{
match: /Content-Security-Policy/,
fn: function (match) {
return "DISABLED-Content-Security-Policy";
}
}
],
If you're really smart you could inject the correct CSP rules that permit browser-sync to do its stuff. Perhaps one diligent soul will end up writing a plugin to do just this?
来源:https://stackoverflow.com/questions/30233218/browser-sync-is-blocked-by-chrome-csp