chrome.storage.sync.get(['player_info'], (data) => {
console.log('search')
console.log(data)
// data = list of possible players
let player_arr = data.player_info
for (let i = 0; i < player_arr.length; i++) {
document.getElementById("card-wrapper").innerHTML +=
`<div onclick="alert('clicked')" class="player_option">
<center>
<div class="card-img-small">
<a href="#">
<img id=\"player_img\" src="${player_arr[i].profile_img}" class="img-responsive">
</a>
</div>
</center>
<div class="card-body">
<div id="player-name" class="price-small">
${player_arr[i].name}
</div>`
}
})
我正在使用上面的代码动态渲染某些项目。
在div
包装器中,我添加了一个alert
函数以检查它是否有效,但是什么也没有发生。我检查了元素,它看起来像这样:
<div onclick="alert('clicked')" class="player_option">
<center>
<div class="card-img-small">
<a href="#">
<img id="player_img" src="https://fmdataba.com/images/p/4348.png" class="img-responsive">
</a>
</div>
</center>
<div class="card-body">
<div id="player-name" class="price-small">
Paul Pogba
</div></div></div>
该函数似乎已正确嵌入,但是没有发生alert
。有帮助吗?
编辑
实际上意识到我遇到此错误:Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
我正在构建Chrome扩展程序
答案 0 :(得分:0)
在chrome应用和扩展程序中,内容安全策略不允许使用内联JavaScript。因此,您必须将javascript放在.js文件中,并将其包含在HTML中。
您必须改为使用js事件监听器。看看这个: Refused to execute inline event handler because it violates CSP. (SANDBOX)
如果您仍然想在onClick
属性中使用js,还可以更改Content Security Policy
。查看:“放松默认策略”下的Content Security Policy (CSP)。