我正在尝试为firefox创建一个待办事项扩展,我需要在单击删除按钮时触发一个函数(第8行)。
function viewPrevious(){
var prom = browser.storage.sync.get(null);
prom.then((res) => {
var text = '<ul class="list-group list-group-flush">';
var i;
for (i = 0; i < res.todos.length; i+=4) {
text+='<ul class="list-group list-group-flush"><li class="list-group-item">'+res.todos[i]+' '+res.todos[i+1]+' '+res.todos[i+2]+'</li>';
text+='<button type="button" class="btn btn-primary" onClick="myFunc" id='+i+'">Delete</button>';
}
text+='</ul>';
document.getElementById("oldTodos").innerHTML = text;
window.onload=function(){
console.log("KKOO");
var promii = browser.storage.sync.get(null);
promii.then((res) => {
for(i=0;i<res.todos.length;i+=4){
console.log("redda");
document.getElementById(i.toString()).addEventListener('click',function(){
console.log('kjk'+i);
var removingItem = browser.storage.sync.remove(i);
removingItem.then(function(){
viewPrevious();
});
});
}
});
}
});
}
我在第8行添加了onClick =“myFunc”,函数是
function myFunc(){
console.log("ABC");
}
当我运行它并单击按钮时,它会给我以下错误
Content Security Policy: The page’s settings blocked the loading of a resource at self (“script-src”). Source: onclick attribute on BUTTON element.
我尝试使用元标记并提供script-src 'unsafe-inline'
,但它也无效。我对这个content security policy
有没有其他方法可以完成这项工作,或者我做错了什么?
答案 0 :(得分:0)
您的问题是HTML onclick属性。要正确执行此操作,您需要使用addEventListener,就像您在稍后的单击侦听器上一样。
// Untested, but it should put you on the correct path
var ul = document.createElement('ul');
ul.classList.add('list-group', 'list-group-flush');
var i;
for (i = 0; i < res.todos.length; i+=4) {
// I'm ignoring <ul class="list-group list-group-flush"> from your example, because
// this doesn't look like you intend to be nesting lists
var li = document.createElement('li';
li.classList.add('list-group-item');
// In your example, you had left an open XSS vulnerability by simply
// concatenating user todos with your markup, textContent is much safer
li.textContent = res.todos[i]+' '+res.todos[i+1]+' '+res.todos[i+2];
ul.appendChild(li);
var button = document.createElement('button');
button.classList.add('btn', 'btn-primary');
button.addEventListener('click', myFunc);
button.id = i;
ul.appendChild(button);
}
document.getElementById("oldTodos").innerHTML = '';
document.getElementById("oldTodos").appendChild(ul);