admin管理员组文章数量:1323529
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:
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="mon/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(".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/ment.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', "/"+ $("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": ["mon/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=".php?goto=newpost&t=555954" id="thread_gotonew_555954" target="_newtab"><img class="inlineimg" src="/img/icons/ment.gif" alt="Go to first new post" border="0"></a>
<a href=".php?goto=newpost&t=555954" id="thread_title_555954" target="_newtab">[All Gamez] [Frozen Synapse] S [...]</a>
</div>
If needed i can provide the full source code.
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:
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="mon/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/ment.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": ["mon/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&t=555954" id="thread_gotonew_555954" target="_newtab"><img class="inlineimg" src="/img/icons/ment.gif" alt="Go to first new post" border="0"></a>
<a href="http://gaming.ngi.it/showthread.php?goto=newpost&t=555954" id="thread_title_555954" target="_newtab">[All Gamez] [Frozen Synapse] S [...]</a>
</div>
If needed i can provide the full source code.
Share Improve this question edited Apr 27, 2013 at 2:39 blahdiblah 34k21 gold badges101 silver badges153 bronze badges asked Aug 23, 2012 at 10:37 ClaudioClaudio 4962 gold badges12 silver badges36 bronze badges 11- 1 Any chance you could link to a version of the screenshot that's large enough to actually be readable? It's not much use to the question if I can't read any of the text. – Anthony Grist Commented Aug 23, 2012 at 10:42
- Just edited the question adding a link to the high resolution :) check the text "Here's a screenshot of the console log:". It's clickable now. – Claudio Commented Aug 23, 2012 at 10:43
-
Can you share your manifest.json file? Maybe there is something wrong with
content_security_policy
field. – KiL Commented Aug 23, 2012 at 12:02 - Added the code of manifest.json – Claudio Commented Aug 23, 2012 at 12:52
-
2
Hint: The scraped page may contain
<script>
blocks and/or inline event handlers. Hint 2: The page references images via relative URLs. – Rob W Commented Aug 23, 2012 at 12:55
1 Answer
Reset to default 9Let's start with the easiest problem:
Refused to execute inline script because ...
$('div', this)
selects all <div>
elements within a <td>
. In the source code you provided, the following event handler can be found:
<div class="smallfont"> <span style="cursor:pointer" onclick="window.open('member.php?u=47995', '_self')">K4raMong</span> </div>
By the default Content Security policy, this is forbidden. To get rid off the error, just remove the attribute before inserting it in the document:
element.removeAttribute('onclick'); // in jQuery: $element.removeAttr('onclick');
Why are these images loaded? I didn't put them in the document
Before jQuery/JavaScript can manipulate DOM, it must be parsed first. In your code, this work is implicitly done at the var TDs = $(.., data)
. line. This parsing is approximately equal to:
var dummy = document.createElement('div'); // Container
dummy.innerHTML = data;
Ever heard about preloading images? That is a useful feature to cache images, so that they're ready when needed. This can be done using (new Image).src='...';
. The created <img>
element doesn't have to be inserted in the document.
In your case, this is undesired behaviour, because these images are looked up in your extension. This is caused by the fact that your web page makes use of relative URLs, rather than absolute ones. When using relative URLs, the expected location of the resources depends on the location of the current document.
How to fix it
Do not use jQuery. Since you're writing a Chrome extension, you do not need to worry about cross-browser patibility. jQuery uses the innerHTML
trick to parse HTML, which failed, as I've previously shown.
JavaScript has the DOMParser
object, which can be used as follows since Chrome 30:
var doc = (new DOMParser).parseFromString(data, 'text/html');
You can skip the manual conversion from string to document using the responseType
property, as shown below.
Arriving at the solution
As you already know, cross-site requests are possible in Chrome extensions, provided that the URL is correctly added to the permissions
section in the manifest file. We're going to use a feature introduced in XMLHttpRequest level 2, namely the responseType
attribute.
// 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();
You can easily rewrite your code to use native DOM and JavaScript instead of jQuery. Most use jQuery for the selector engine, but most often, it can also be implemented using element.querySelectorAll
. After getting the document using var doc = xhr.response;
, do the following:
var TDs = doc.querySelectorAll('td[id*="td_threadtitle_"]');
var html = '';
[].forEach.call(TDs, function(td) {
// etc, etc. Do your job
});
Do you see var html = '';
? That's good practice, regardless of whether you're using jQuery or not. Never do element.innerHTML += ...;
or even worse $element.html($element.html() + ...);
in a loop. The browser will have a hard time with rendering it over and over again, and you -as a user- notice performance degradation.
版权声明:本文标题:javascript - Console shows error about Content Security policy and lots of failed GET requests - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742130799a2422149.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论