3

I'm actually working on my first Chrome Extension and even if it run smooth i got a lot of error from the get() function i'm using to retrieve some data and an annoying error about the security of the code.

Here's a screenshot of the console log: Console Log

Following there's the code involved:

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>

popup.js

This script start making a $.get() to a remote web page. The content of the variable data can be found here

$.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/>" );
        });
    });
});

Here you can find the HTML after all the manipulation from jquery.

Honestly i cannot understand why these error show, especially the one related to the security. I've not used any inline code in my 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/*"
    ]
}

The following is a piece of HTML code that will be rendered into the popup window after all the manipulation. All the div is similar to this, just the url changes:

<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>

If needed i can provide the full source code.

4

1 回答 1

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');

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

在 jQuery/JavaScript 可以操作 DOM 之前,必须先对其进行解析。在您的代码中,这项工作在var TDs = $(.., data). 线。这个解析大约等于:

var dummy = document.createElement('div'); // Container
dummy.innerHTML = data;

听说过预加载图像吗?这是缓存图像的有用功能,以便在需要时准备好它们。这可以使用(new Image).src='...';. 创建的<img>元素不必插入到文档中。

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

如何修复它

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

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

var doc = (new DOMParser).parseFromString(data, 'text/html');

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

到达解决方案

permissions如您所知,只要 URL 正确添加到清单文件中的部分,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();

您可以轻松地重写代码以使用本机 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
});

你看到了var html = '';吗?这是一个很好的做法,无论您是否使用 jQuery。永远不要在循环中做element.innerHTML += ...;,甚至更糟。$element.html($element.html() + ...);浏览器将很难一遍又一遍地渲染它,并且您 - 作为用户 - 会注意到性能下降。

于 2012-08-23T22:34:41.487 回答