Can't get feed in Windows 8 app - javascript

I am creating blog reader app for Windows 8 by using RSS feeds. Part of code:
function downloadBlogFeed() {
WinJS.xhr({ url: "http://feeds.feedburner.com/CssTricks" }).then(function (rss) {
var items = rss.responseXML.querySelectorAll("item");
for (var n = 0; n < items.length; n++) {
var article = {};
article.title = items[n].querySelector("title").textContent;
var thumbs = items[n].querySelectorAll("thumbnail");
if (thumbs.length > 1) {
article.thumbnail = thumbs[1].attributes.getNamedItem("url").textContent;
article.content = items[n].textContent;
articlesList.push(article);
}
}
});
}
So, my app can't read feed from FeedBurner. I get this error
Can't load http://feeds.feedburner.com/~d/styles/itemcontent.css. An app can’t load remote web content in the local context.
I've tried http://feeds.feedburner.com/CssTricks?format=xml and http://feeds.feedburner.com/CssTricks?fmt=xml, but the same error.
EDIT: Full code: http://jsfiddle.net/8n67y/

The error you're encountering isn't because you can't read from Feedburner. It's because somewhere in the content that you're attempting to load into the DOM is a reference to a CSS file on the web (itemcontent.css).
When you're operating in the local context, you cannot dynamically load script or CSS from the web, because that poses security risks in the local context.
See here:
http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx
and here:
http://msdn.microsoft.com/en-us/library/windows/apps/hh465373.aspx
for more information on the differences between local and web context, and the restrictions that apply to each.
For your particular case, I think what you should try is parsing the content further (you can set a breakpoint in the above code to examine the XML content being returned by the feed) to determine where the CSS file reference is being returned and either remove it programmatically, if it's in a consistent place, or find another means of eliminating the CSS reference, which appears to be what's causing the exception (based on the limited information above).

What you are trying to do can be done with the below code, instead of WinJS.xhr use the xmlHTTPRequest.
The code below is part of the code I use um my RSS reader and it works pretty well in all situations, we can donwload pictures, text, links.. whatever you can find in the feed (http://feeds.feedburner.com/CssTricks) getting the thumbnails, and all worked fine.
Also I tested it with the following modification,
function connectToURL() {
var url = "";
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
return;
}
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET", url,true);
xmlHttp.send(null);
}
// your job will actually start on this one...
function stateChanged() {
if(xmlHttp != null )
if (xmlHttp[item.key].readyState == 4 ) {
try {
var xmlDoc = xmlHttp.responseXML.documentElement.getElementsByTagName("TAGYOUWANTTOGET");
for (var i = 0; i < xmlDoc.length; i++) {
xmlDoc[i].getElementsByTagName("TAG")[0].childNodes[0].nodeValue
}
} catch (e) {
//work on the exception
}
}
}
}
function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}
catch(e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

Related

GetElementbyId from XMLHttpRequest() in IE 8.0

i am developing youtube user history view functionality, now here i am trying to get YouTube userId using youtubeInfoUri and requested token,
here this code is working awesome in FF and Chrome, but fail in IE
function getDataFromXML() {
try {
youTubeUserInfoUri += acToken; // global variable currently.
// i.e youTubeUserInfoUri = "https://gdata...."
//IE : if URI contain https then exception thrown :
/* description : $lineinfo is undefined */
/* Name : TypeeEror */
//To handle this :
youTubeUserInfoUri = youTubeUserInfoUri.replace("https", "http");
var request = new XMLHttpRequest();
request.open("GET", youTubeUserInfoUri, false);
request.timeout = 3000;
request.onprogress = function () { };
request.ontimeout = function () { };
request.onerror = function () { };
request.send();
if (request.status == 200) {
var xml = request.responseXML;
here in xml : i got childnodes = {count 0}; item =invalid number of parameters
Now I m totally blank here , dont have any idea why this happend..
if (xml == null) {
//if Google account dont have youtube account / error 401 found ,
showShortNotification("YouTube", "current user is not linked with YouTube", "error");
} else {
//Browser exception handle :
//TagName understanding is different by FF and & Chrome browser,
var users = xml.getElementsByTagName("username"); // here check for Chrome: Firefox will not understand this tag name
if (users.length == 0) { // if its length is 0 means no elements found, so try for next tag method
users = xml.getElementsByTagName("yt:username"); // here firefox understand this method
/* In IE : during debug point : here users = Item : Invalid number of parameters.*/
}
for (var i = 0; i < users.length; i++) {
var youtubeUserid = (users[i].childNodes[0].nodeValue);
YoutubeUserHistoryFetch(youtubeUserid);
}
}
}
} catch (e) {
alert("Error found" + e);
}
}
I also tried
[1] new window.XDomainRequest();
[2] try changing Internet Explorer Trusted Site Zones settings (Internet Explorer Options->Security-> Trusted Sites + Custom Level , scroll down and change Access data sources across domains value to Enable
Xml Response Text :
.....<yt:maxUploadDuration seconds="930" />
<yt:statistics lastWebAccess="1970-01-01T00:00:00.000Z" subscriberCount="9" videoWatchCount="0" viewCount="0" totalUploadViews="70" />
<media:thumbnail url="http://yt4.ggpht.com/-pFKkUesgV-Q/AAAAAAAAAAI/AAAAAAAAAAA/I23mZGfUo-A/s88-c-k-no/photo.jpg" />
<yt:username>saun4frsh</yt:username>
I need
Please help, if you have any idea to solve this.
Only problem with Internet Explorer , Same code working fine in Chrome and FF.
I have IE8, and win 7 OS.
Use This Code : Specially For IE 8 , 100% working
function getDataFromXML() {
try {
youTubeUserInfoUri += acToken;
if (navigator.userAgent.search("MSIE") >= 0) {
var rssData = httpGet();
var youtubeUserid = convertToArrayForIE(rssData.getElementsByTagName('yt:username'));
YoutubeUserHistoryFetch(youtubeUserid[0]);
} else {
//Rest ur code for FF/Chrome Old code
}
}
catch{}
}
function httpGet() {
youTubeUserInfoUri = youTubeUserInfoUri.replace("https", "http"); //IE not allows https : security issue.
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', youTubeUserInfoUri, false);
xmlHttp.send();
if (window.DOMParser) {
var parser = new DOMParser();
var doc = parser.parseFromString(xmlHttp.responseText, 'text/xml');
return doc;
}
else {
var xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
xmlDocument.async = false;
xmlDocument.loadXML(xmlHttp.responseText);
return xmlDocument;
}
}
function convertToArrayForIE(htmlCollection) {
var nodes = [];
var collectionLength = htmlCollection.length;
for (var i = 0; i < collectionLength; i++) {
nodes.push(htmlCollection.item(i).firstChild.text);
}
return nodes;
}

WinJS.xhr returning XML string as text (including \n\r tags), instead of a responseXML

I'm starting up playing with Win8 development and I'm stucked in a problem since yesterday.
I've followed the MSDN example HERE to grab the data, I can retrieve the data (therefore, isn't a connection limitation issue) but the problem is that regardless the settings I use, it always retrieve data as plain text, including \r\n characters.
I assume that if I could retrieve the structured XML would make my job easier, so I'm hoping you folks can put some lights on what I'm doing wrong.
Here's my code snippet:
<div id="xhrReport"></div>
<script>
var xhrDiv = document.getElementById("xhrReport");
xhrDiv.style.color = "#000000";
WinJS.xhr({ url: "http://www.w3schools.com/xml/note.xml", responseType: "responseXML"})
.done(
function complete(result) {
var xmlResponse = result.response;
xhrDiv.innerText = "Downloaded the page";
xhrDiv.style.backgroundColor = "#00FF00"; //here goes my breakpoint to check response value
},
function error(result) {
xhrDiv.innerHTML = "Got error: " + result.statusText;
xhrDiv.style.backgroundColor = "#FF0000";
},
function progress(result) {
xhrDiv.innerText = "Ready state is " + result.readyState;
xhrDiv.style.backgroundColor = "#0000FF";
}
);
</script>
Here's the value of xmlResponse
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<!-- Edited by XMLSpy® -->\r\n<note>\r\n\t<to>Tove</to>\r\n\t<from>Jani</from>\r\n\t<heading>Reminder</heading>\r\n\t<body>Don't forget me this weekend!</body>\r\n</note>\r\n"
And HERE is a similar question, which seems to be working using the responseXML responseType (although it's not documented #MSDN guide).
Some things I already tried:
Use a responseType as 'document' (as per the MSDN guide) and then retrieve result.responseXML;
Omit the responseType argument;
Use the approach above.
Now, I ran out of ideas. Any thoughts?
Try To use the following code to get the tags you want to play... (I believe it will do exactly what you want/need, connecting to a webpage and than work on the result based o the webpage/xml tags
function connectToURL(){
var url = "";
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
return;
}
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET", url,true);
xmlHttp.send(null);
}
// your job will actually start on this one...
function stateChanged() {
if(xmlHttp != null )
if (xmlHttp[item.key].readyState == 4 ) {
try {
var xmlDoc = xmlHttp.responseXML.documentElement.getElementsByTagName("TAGYOUWANTTOGET");
for (var i = 0; i < xmlDoc.length; i++) {
xmlDoc[i].getElementsByTagName("TAG")[0].childNodes[0].nodeValue
}
} catch (e) {
//work on the exception
}
}
}
}
function GetXmlHttpObject(){
var xmlHttp=null;
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
I think you should set an option for responseType : "document" just like:
WinJS.xhr({
url: "http://www.capital.bg/rss/?rubrid=" + groupId,
responseType:"document"
}).then(function (result) {
console.dir(result.response);
});

Safari Won't Work With Microsoft.XMLDOM ActiveX Object

I'm designing a client side script that will read an XML file and display it, like this:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
function loadXML(xmlFile) {
xmlDoc.async = "false";
xmlDoc.onreadystatechange = verify;
xmlDoc.load(xmlFile);
}
function verify() {
if(xmlDoc.readyState != 4) {
return false;
}
}
function traverse(tree) {
if(tree.hasChildNodes()) {
document.write('<ul><li>');
document.write('<b>' + tree.tagName + ': </b>');
var nodes = tree.childNodes.length;
for(var i = 0; i < tree.childNodes.length; i++) {
traverse(tree.childNodes(i));
}
document.write('</il></ul>');
} else {
document.write(tree.text);
}
}
function initTraverse(file) {
loadXML(file);
var doc = xmlDoc.documentElement;
traverse(doc);
}
When I fired Safari I saw that nothing was displayed, then I've opened the Error Console and what I got was this:
ReferenceError: Can't find variable: ActiveXObject
What should I do to make this work?
PS: I would prefer if this page could be capable of running at Mobile Safari
ActiveXObject do not work outside of internet explorer.
There are a few alternative xml parser's and handlers like E4X. Although E4X is currently only done in firefox (https://developer.mozilla.org/En/E4X/Processing_XML_with_E4X).
If using jQuery is an option then you can look into marcgrabanski.com/articles/jquery-makes-parsing-xml-easy
Some interesting stuff going on there. Most interesting is the async = false line. You probably want to re-consider that bit. In order to change to an asynchronous request, you would have to re-write some other code and remove the document.write calls.
Regardless, here is a (untested but hopefully) drop in replacement for what you have using XMLHttpRequest instead of an xml document.
var xmlDoc = null;
function loadXML(xmlFile) {
var request = new XMLHttpRequest();
request.open('GET', xmlFile, false); // false is synchronous
request.send();
xmlDoc = request.responseXML;
}
You may have to do some debugging...
You should have something cross-browser compatible with either DOMParser or DOMDocument. Of course, I'm not sure if you're wanting to parse a XML URL or a XML string. For a XML URL, I recommend:
if (window.XMLHttpRequest) return new window.XMLHttpRequest();
else if (window.ActiveXObject) {
// the many versions of IE's XML fetchers
var AXOs = [
'MSXML2.XMLHTTP.6.0',
'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP',
'MSXML.XMLHTTP'
];
for (var i = 0; i < AXOs.length; i++) {
try { return new ActiveXObject(AXOs[i]); }
catch() { continue; }
}
return null;
}
For a XML string, this code block would work better:
if (window.DOMParser) return (new DOMParser()).parseFromString(str, 'text/xml');
else if (window.ActiveXObject) {
var doc;
// the many versions of IE's DOM parsers
var AXOs = [
'MSXML2.DOMDocument.6.0',
'MSXML2.DOMDocument.5.0',
'MSXML2.DOMDocument.4.0',
'MSXML2.DOMDocument.3.0',
'MSXML2.DOMDocument',
'Microsoft.XMLDOM',
'MSXML.DOMDocument'
];
for (var i = 0; i < AXOs.length; i++) {
try { doc = new ActiveXObject(AXOs[i]); break; }
catch() { continue; }
}
if (!doc) return createElement('div', null);
if (doc.async) doc.async = false;
doc.loadXML(str);
return doc;
}
return createElement('div', null);
The DOMDocument objects do support a load() method for loading XML from a URL, but it's a different syntax than the XMLHttpRequest and XMLHTTP methods.
The DOMDocument appears (at least from the MSDN docs) to also contain the XMLHTTP methods, so you could interlace DOMDocument in the AXOs array, but I'm not certain about that. Plus, I can't imagine DOMDocument being in place without XMLHTTP.

Running JavaScript downloaded with XMLHttpRequest

I have a site that loads information using the XMLHttpRequest when a user clicks a link. The system works well but I would like to be able to execute JavaScript gathered in this process.
This is a problem as I would like to download the scripts 'on demand' if it were, rather than loading them all when the page is loaded.
Thanks for any help
I believe the recommended solution is something like this:
function include(scriptUrl)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", scriptUrl);
xmlhttp.onreadystatechange = function()
{
if ((xmlhttp.status == 200) && (xmlhttp.readyState == 4))
{
eval(xmlhttp.responseText);
}
};
xmlhttp.send();
}
Or something like it.
However, be wary of this approach. It's vulnerable to cross-site scripting, which can open you (and your users) up to all sorts of nastiness. You'll want to take suitable precautions.
Recently I found the answer (It works in Chrome, in another browsers it was not tested).
You can create dataURL string and put it into src attribute of script element.
var xhr = XMLHttpRequest(),
doc = document;
xhr.open('GET', pathToJSFile, true);
xhr.onload = function () {
var script = doc.createElement('script'),
base64 = 'data:application/javascript;base64,';
try {
base64 += btoa(data.responseText);
} catch (e) {
// script file may contain characters that not included in Latin1
var symbols = data.responseText.split('');
for (var i = 0, l = symbols.length; i < l; i++) {
var symbol = symbols[i];
// here we are trying to find these symbols in catch branch
try {
btoa(symbol);
} catch (e) {
var code = symbol.charCodeAt(0).toString(16);
while (code.length < 4) {
code = '0' + code;
}
// replace original symbol to unicode character
symbols[i] = '\\u' + code;
}
}
// create new base64 string from string with replaced characters
base64 += btoa(symbols.join(''));
} finally {
script.src = base64;
// run script
doc.body.appendChild(script);
}
};
xhr.send();
You can subscribe to xhr.onprogress to show progress bar.
Update. You can download your script file as blob, and then create blob-url.
var xhr = XMLHttpRequest(),
doc = document;
xhr.responseType = 'blob';
xhr.open('GET', pathToJSFile, true);
xhr.onload = function () {
var script = doc.createElement('script'),
src = URL.createObjectURL(xhr.response);
script.src = src;
doc.body.appendChild(script);
};
xhr.send();
You can run script downloaded in form of a string using
eval()
However I would recommend you to add new
<script src='..'></script>
to your document and have a callback which will be called when it will be downloaded. There are many utils and jquery plug-ins for that.
I had the challenge on a mobile web-project, the magic was to set "overrideMimeType".
This has been verified to work on Android 4.1 to Android 6.0.
var head = document.getElementsByTagName('head');
var injectedScript = document.createElement('script');
head[0].appendChild(injectedScript);
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
injectedScript.innerHTML = myRequest.responseText;
//run a function in the script to load it
}
};
function start(){
myRequest.open('GET', 'javascript-url-to-download', true);
myRequest.overrideMimeType('application/javascript');
myRequest.send();
}
start();
You would need to use eval to parse the javascript from the XHR, note that this is EXTREMELY dangerous if you don't have absolute trust in the source of the javascript.

TypeError: Value undefined (result of expression xmlDoc.load) is not object

I am trying to load an XML file using Javascript and I have yet to find a good function that works in IE, Firefox, and Safari. The load function I am currently using is basically the one straight out of the w3schools tutorials:
http://www.w3schools.com/XML/tryit.asp?filename=tryxml_dom_createelement
The exact code looks like:
if (window.ActiveXObject)
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation.createDocument)
{
xmlDoc=document.implementation.createDocument("","",null);
}
else
{
alert('Your browser cannot handle this script');
}
xmlDoc.async=false;
xmlDoc.load(dname);
Where dname = the url of the xml file. This code gets a "TypeError: Value undefined (result of expression xmlDoc.load) is not object." in Safari.
I have also tried the code on this site:
http://developer.apple.com/internet/webcontent/xmlhttpreq.html
However, it yields a null XML file. Can anyone help?
Sounds like the problem is that Safari does not support document.implementation.createDocument as a method to fetch and load XML sources. You must use an XMLHttpRequest to fetch and parse the XML AFAIK.
I've tried a modified version of the code from the Apple tutorial you linked and it seemed to work for me. This code is not the best in the world, and it's missing a lot of error handling, but it's the only proof of concept I had on hand.
Note: I highly recommend using a library. There are browser inconsistencies abound with XMLHttpRequests and XML parsing. It's worth the investment!
For a non library version I used a modified version of the safari code to get the XMLHttpRequest:
function getXHR(url,callback) {
var req = false;
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.onreadystatechange = function() { callback( req ) };
req.open("GET", url, true);
req.send("");
}
}
Grabbing the XML from the result is not without its own quirks as well:
function getXML( response ) {
if( response.readyState==4 ) {
//Get the xml document element for IE or firefox
var xml;
if ( response.responseXML ) {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(response.responseText);
} else {
xml = response.responseXML;
}
return xml;
}
return null;
}
Finally use what you get:
function callback( response ) {
var xmlDoc = getXML( response );
if( xmlDoc ) {
//do your work here
...
}
}
If you still find yourself having trouble there are a few things you can check that will likely solve your problem.
Did you set your content type to text/xml?
Is your request actually making it to the server and back?
When you alert/examine the responseText, do you see anything that does not belong?
Is your XML properly formatted? Run it through a validator.
Best of luck! Cheers.
You might want to look at XML for <Script>. I've seen some posts that indicate that they've solved the problem on Safari with it.

Categories