【发布时间】:2018-12-03 14:59:15
【问题描述】:
我在 html 文件中使用 React 编写了 javascript。我可以在本地网络浏览器中成功执行,但是当我将其上传到 chrome 扩展程序时,它会报告如下错误:
拒绝执行内联脚本,因为它违反了以下内容安全策略指令:“script-src 'self' https://cdnjs.cloudflare.com'unsafe-eval'”。启用内联执行需要“unsafe-inline”关键字、哈希(“sha256-lTIMNTuZotM+E9A4AGJeqMEUWkdv1blKxgUpdRd8jwk=”)或随机数(“nonce-...”)。
我尝试在 manifest.json 文件中添加 'unsafe-inline' 关键字,但仍然出现同样的错误。
我的 manifest.json 文件是这样的:
{
"manifest_version": 2,
"name": "Price Tracker",
"description": "This extension will track the price of a page",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "index.html"
},
"permissions": [
"tabs",
"activeTab",
"identity",
"identity.email",
"http://34.204.12.200:5000/"
],
"background": {
"page": "index.html"
},
"content_security_policy": "script-src 'self' 'unsafe-inline' https://ajax.googleapis.com http://cdnjs.cloudflare.com; object-src 'self'",
"content_scripts": [
{
"matches": ["http://cdnjs.cloudflare.com/*"],
}
],
"options_page": "copy.html"
}
我的 copy.html 文件是:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Display extends React.Component {
constructor(props){
super(props);
this.state={
urls: []
}
}
componentDidMount(){
console.log("test");
var xhr = new XMLHttpRequest();
var self = this; //why?
xhr.open("POST", "http://34.204.12.200:5000/get_all_tracked", true);
console.log("test1");
// if (xhr.readyState != 4) {
// console.log("test2");
// return;
// }
xhr.onreadystatechange = function(e){
console.log("test5");
if(xhr.readyState===4 && xhr.status===200){
console.log("test3");
self.setState(
{
urls: JSON.parse(this.response)
});
}
}
// console.log("test3");
// self.setState(
// {
// urls: JSON.parse(this.response)
// });
console.log("test4");
// xhr.open("POST", "http://34.204.12.200:5000/get_all_tracked", true);
var params = {'email': "tongxiong99@gmail.com"};
xhr.send(JSON.stringify(params));
}
render() {
if (this.state.urls === undefined || this.state.urls.length == 0) {
return (<div>You are not tracking any pages.</div>);
}
return;
}
}
ReactDOM.render(
<Display />,
document.getElementById('root')
);
</script>
</head>
<body>
<div id="root"></div>
</body>
</html>
谁能解释我应该怎么做?谢谢!
【问题讨论】:
-
不要使用内联脚本。使用单独的 js 文件并在脚本标签的 src 属性中指定它。
-
由于manifest 3不允许执行内联脚本,请查看stackoverflow.com/questions/67439012/…
标签: javascript html reactjs google-chrome-extension