创建按钮时Google Extension CSP内联javascript错误(添加的每个网站一个按钮)
我正在制作一个扩展,由用户从指定网站下载文件。我现在正在做的是制作网站列表,并在每个网站旁边设置一个按钮,以便从该网站下载文件。我想问题是我不了解chrome扩展的内联策略,但每次点击我都会得到: 拒绝执行内联事件处理程序,因为它违反 遵循内容安全策略指令:“脚本src'self” chrome扩展资源:“ 我已经环顾了这个错误,尝试了不同的解决方案,但没有成功。有什么帮助吗?谢谢大家! 代码如下:创建按钮时Google Extension CSP内联javascript错误(添加的每个网站一个按钮),javascript,google-chrome-extension,Javascript,Google Chrome Extension,我正在制作一个扩展,由用户从指定网站下载文件。我现在正在做的是制作网站列表,并在每个网站旁边设置一个按钮,以便从该网站下载文件。我想问题是我不了解chrome扩展的内联策略,但每次点击我都会得到: 拒绝执行内联事件处理程序,因为它违反 遵循内容安全策略指令:“脚本src'self” chrome扩展资源:“ 我已经环顾了这个错误,尝试了不同的解决方案,但没有成功。有什么帮助吗?谢谢大家! 代码如下: //printURLs receives an array of TrackedWebs
//printURLs receives an array of TrackedWebsites and print the urls on the main popup
//It prints also the button to download the files from that website
function printURLs(websites){
var i;
var elem = document.getElementById("websitesList");
console.log(websites);
for (i = 0; i<websites.length; i++){
var node = document.createElement("li");
var url = document.createTextNode(websites[i].get_URL);
var downloadButton = document.createElement('input');
downloadButton.setAttribute('type','button');
downloadButton.setAttribute('name','down'+i);
downloadButton.setAttribute('value','DL');
downloadButton.setAttribute("onclick","clickDownloadFiles(websites[i])");
console.log(websites[i].get_URL);
node.appendChild(url);
node.appendChild(downloadButton);
elem.appendChild(node);
}
}
function clickDownloadFiles(website){
var filesURLs = retrieveFilesURLs(website);
downloadFiles(filesURLs);
}
//printURLs接收跟踪网站的数组,并在主弹出窗口上打印URL
//它还打印从该网站下载文件的按钮
函数printURL(网站){
var i;
var elem=document.getElementById(“网站列表”);
console.log(网站);
for(i=0;i将字符串指定给onclick
属性是隐式求值,因此它违反了
消除此错误的正确方法是使用函数
downloadButton.setAttribute("onclick", "clickDownloadFiles(websites[i])");
// should be
downloadButton.onclick = function(e) { clickDownloadFiles(websites[i]); };
当前方法的另一个问题是,所有onclick
处理程序都共享相同的i
变量。如果websites
对象是真数组,只需使用该方法即可。否则,必须将i
变量作为元素属性存储
websites.forEach(function(website, i) {
...
downloadButton.onclick = function(e) {
clickDownloadFiles(website);
};
...
});
阅读关于循环中的闭包和关于的文章。我在发布此文章之前做过,我不明白我做错了什么,因为所有内容都在一个外部javascript文件中。无论如何,谢谢;)您已经解决了这个问题,但要说得非常清楚:“所有内容都在一个外部javascript文件中”不正确。您试图使用setAttribute(onclick)行再次将内联脚本注入到页面中。请查看正在注入的值(单击DownloadFiles(…)是JavaScript吗?这就是问题所在。好吧,我现在明白了。通过设置该属性,函数就像是在html中定义的一样。谢谢你:谢谢!它与forEach完美配合,因为它是一个真正的数组。你能解释为什么函数(e)中的(e)是如果不使用它?如果你愿意,可以省略e
。出于习惯,我经常在事件侦听器中声明“e”、“ev”或“event”。