我正在制作一个Chrome扩展,它将打开新标签页中的所有链接.
的manifest.json
{ "name": "A browser action which changes its icon when clicked.","version": "1.1","permissions": [ "tabs","<all_urls>" ],"browser_action": { "default_title": "links",// optional; shown in tooltip "default_popup": "popup.html" // optional },"content_scripts": [ { "matches": [ "<all_urls>" ],"js": ["background.js"] } ],"manifest_version": 2 }
popup.html
<!doctype html> <html> <head> <title>My Awesome Popup!</title> <script> function getPageandSelectedTextIndex() { chrome.tabs.getSelected(null,function(tab) { chrome.tabs.sendRequest(tab.id,{greeting: "hello"},function (response) { console.log(response.farewell); }); }); } chrome.browserAction.onClicked.addListener(function(tab) { getPageandSelectedTextIndex(); }); </script> </head> <body> <button onclick="getPageandSelectedTextIndex()"> </button> </body> </html>
background.js
chrome.extension.onRequest.addListener( function(request,sender,sendResponse) { console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension"); if (request.greeting == "hello") updateIcon(); }); function updateIcon() { var allLinks = document.links; for (var i=0; i<allLinks.length; i++) { alllinks[i].style.backgroundColor='#ffff00'; } }
最初我想突出显示页面上的所有链接或以某种方式标记它们;但是我收到错误“拒绝执行内联脚本,因为Content-Security-Policy”.
当我按弹出窗口内的按钮时,我得到这个错误:拒绝执行内联事件处理程序,因为Content-Security-Policy.
解决方法
“manifest_version”的后果之一是2,默认情况下启用
Content Security Policy. Chrome开发人员选择严格执行此操作,并始终禁止使用内置JavaScript代码 – 只允许在外部JavaScript文件中执行代码(以防止扩展中的
Cross-Site Scripting vulnerabilities).因此,不要在popup.html中定义getPageandSelectedTextIndex()函数,您应该将其放入popup.js文件并将其包含在popup.html中:
<script type="text/javascript" src="popup.js"></script>
< button onclick =“getPageandSelectedTextIndex()”>必须改变,onclick属性也是一个内联脚本.您应该分配ID属性:< button id =“button”> ;.然后在popup.js中,您可以将该事件处理程序附加到该按钮:
window.addEventListener("load",function() { document.getElementById("button") .addEventListener("click",getPageandSelectedTextIndex,false); },false);