控制台显示有关内容安全策略和许多失败的GET请求的错误

the*_*ius 3 javascript dom google-chrome google-chrome-extension content-security-policy

我实际上正在开发我的第一个Chrome扩展程序,即使它运行顺利,我从get()我用来检索一些数据的函数和代码安全性的烦人错误中得到了很多错误.

这是控制台日志屏幕截图: 控制台日志

以下是涉及的代码:

popup.html

<!doctype html>
<html>
<head>
    <title>NGI Little Helper - Subscribes</title>
    <link rel="stylesheet" href="popup.css">
    <!-- JavaScript and HTML must be in separate files for security. -->
    <script type="text/javascript" src="common/jquery.js"></script>
    <script type="text/javascript" src="popup.js"></script>
</head>

<body>
    <h1>Topics</h1>
    <div id="content">..:: Loading ::..</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

popup.js

此脚本开始创建$.get()远程网页.变量的内容data可以在这里找到

$.get("http://gaming.ngi.it/subscription.php?do=viewsubscription", function(data) {
    var TDs = $('td[id*="td_threadtitle_"]', data);
    $(document).ready(function() {
        $("#content").html("<br/>");
        $.each( TDs, function() {
            //Removes useless elements from the source
            $('img[src="images/misc/tag.png"]', this).remove();
            $('span', this).remove(); //$('span[class="smallfont"]', this).remove();
            $('div[class="smallfont"]', this).remove();
            $('img[src="images/buttons/firstnew.gif"]', this).attr('src', '/img/icons/comment.gif');
            $('a[style="font-weight:bold"]', this).removeAttr("style");
            //Modify the lenght of the strings
            if ($("a[id^='thread_title_']", this).text().length > 35) {
                $("a[id^='thread_title_']", this).text( $("a[id^='thread_title_']", this).text().substring(0, 30) + " [...]" );
            }
            //Modify the URL from relative to absolute and add the target="_newtab"
            $("a[id^='thread_']", this).attr('href', "http://gaming.ngi.it/"+ $("a[id^='thread_']", this).attr('href'));
            $("a[id^='thread_']", this).attr('target', "_newtab");
            //Send the HTML modified to the popup window
            $("#content").html($("#content").html() + $('div', this).wrap("<span></span>").parent().html() +"<br/>" );
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

在这里,你可以在jquery的所有操作之后找到HTML.

老实说,我无法理解为什么会出现这些错误,特别是与安全相关的错误.我的popup.html中没有使用任何内联代码.

的manifest.json

{
    "name": "NGI Little Helper",
    "version": "0.8.5",
    "manifest_version": 2,
    "description": "Extension per gli Utenti del forum gaming.ngi.it",
    "options_page": "fancy-settings/source/index.html",
    "background": {
        "page": "background.html"
    },
    "icons": {
        "16": "img/logo16.png",
        "48": "img/logo48.png",
        "128": "img/logo128.png"
    },
    "content_scripts": [{
        "matches": ["*://gaming.ngi.it/*"],
        "js": ["common/jquery.js", "logo_changer/logo_change.js"],
        "run_at": "document_start"
    }],
    "browser_action": {
        "default_icon": "img/icon.png",
        "default_popup": "popup.html",
        "default_title": "Visualizza Subscriptions"
    },
    "permissions": [
        "*://gaming.ngi.it/*"
    ]
}
Run Code Online (Sandbox Code Playgroud)

以下是一段HTML代码,在所有操作之后将被渲染到弹出窗口中.所有div类似于此,只是网址更改:

<div>

            <a href="http://gaming.ngi.it/showthread.php?goto=newpost&amp;t=555954" id="thread_gotonew_555954" target="_newtab"><img class="inlineimg" src="/img/icons/comment.gif" alt="Go to first new post" border="0"></a>




            <a href="http://gaming.ngi.it/showthread.php?goto=newpost&amp;t=555954" id="thread_title_555954" target="_newtab">[All Gamez] [Frozen Synapse] S [...]</a>

        </div>
Run Code Online (Sandbox Code Playgroud)

如果需要,我可以提供完整的源代码.

Rob*_*b W 9

让我们从最简单的问题开始:

拒绝执行内联脚本,因为......

$('div', this)选择a中的所有<div>元素<td>.在您提供的源代码中,可以找到以下事件处理程序:

<div class="smallfont">
    <span style="cursor:pointer" onclick="window.open('member.php?u=47995', '_self')">K4raMong</span>
</div>

默认情况下,内容安全策略禁止此操作.要摆脱错误,只需在将其插入文档之前删除该属性:

element.removeAttribute('onclick'); // in jQuery: $element.removeAttr('onclick');
Run Code Online (Sandbox Code Playgroud)

为什么要加载这些图像?我没有把它们放在文件中

在jQuery/JavaScript可以操作DOM之前,必须首先解析它.在您的代码中,这项工作是隐式完成的var TDs = $(.., data).线.此解析大约等于:

var dummy = document.createElement('div'); // Container
dummy.innerHTML = data;
Run Code Online (Sandbox Code Playgroud)

有没有听说过预装图片?这是缓存图像的有用功能,以便在需要时准备就绪.这可以使用(new Image).src='...';.创建的<img>元素不必插入文档中.

在您的情况下,这是不受欢迎的行为,因为这些图像会在您的扩展程序中查找.这是因为您的网页使用了相对URL而不是绝对URL.使用相对URL时,资源的预期位置取决于当前文档的位置.

如何解决它

千万不能使用jQuery.由于您正在编写Chrome扩展程序,因此无需担心跨浏览器兼容性.innerHTML正如我之前所示,jQuery使用该技巧来解析失败的HTML.

JavaScript有这个DOMParser对象,从Chrome 30开始可以使用如下:

var doc = (new DOMParser).parseFromString(data, 'text/html');
Run Code Online (Sandbox Code Playgroud)

您可以使用responseType属性跳过从字符串到文档的手动转换,如下所示.

到达解决方案

如您所知,只要将URL正确添加到permissions清单文件中的部分,就可以在Chrome扩展程序中进行跨站点请求.我们将使用XMLHttpRequest级别2中引入的功能,即responseType属性.

// Fetching data
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://gaming.ngi.it/subscription.php?do=viewsubscription');
xhr.onload = function() {
    var doc = xhr.response;
    // Now, you can use jQuery, since the string has been parsed.
    ...
};
xhr.responseType = 'document'; // Chrome 18+
xhr.send();
Run Code Online (Sandbox Code Playgroud)

您可以轻松地重写代码以使用本机DOM和JavaScript而不是jQuery.大多数人使用jQuery作为选择器引擎,但大多数情况下,它也可以使用element.querySelectorAll.获取文档后var doc = xhr.response;,请执行以下操作:

var TDs = doc.querySelectorAll('td[id*="td_threadtitle_"]');
var html = '';
[].forEach.call(TDs, function(td) {
    // etc, etc. Do your job
});
Run Code Online (Sandbox Code Playgroud)

你看到了var html = '';吗?无论你是否使用jQuery,这都是很好的做法.循环中从不做element.innerHTML += ...;甚至更糟$element.html($element.html() + ...);.浏览器将很难一次又一次地呈现它,并且您 - 用户通知性能下降.