I have a gzipped response from a web request that I need to decompress in JavaScript (actually, in the success function of an AJAX call - my code is running in a headless browser, and doesn't have the built-in gzip processing support offered by a full browser). I've been looking around for an answer but I'm a bit stumped.
Ideally, what I'd like to have code for is:
var my_decompressed_string = someGzipDecompressor(xhr.responseText);
I found, what I thought was an answer at JavaScript implementation of Gzip but that may not be the answer I was hoping for. When trying to use the mentioned jsxcompressor library by way of the following code snippet
var my_decompressed_string = JXG.decompress(xhr.responseText);
... I get ...
TypeError: 'undefined' is not an object (evaluating '(new JXG.Util.Unzip(JXG.Util.Base64.decodeAsArray(str))).unzip()[0][0]')
Looking at that function in more detail, if I break up the code being executed by the decompress() function, I get what I assume is something good returned by the inner part ...
JXG.Util.Base64.decodeAsArray(xhr.responseText)
... but undefined returned for the outer part...
JXG.Util.Unzip( ... )
So, that may be a dead end of course, but if anyone knows a way that my original question should be possible, or has had any better luck with jsxcompressor.js I'd appreciate it.
Of course, I can force my AJAX request to return a 'deflate' response but the size of the page (for which I have no control over) is pretty large and requesting gzip is an attempt at speeding up my page load time.
jsxcompressor.js requires base64 encoded string to decompress, you should use:
var my_decompressed_string = JXG.decompress(btoa(xhr.responseText));
if your headless browser does not support btoa then you should use a base64 encoding library, if your node or iojs there are plenty of base64 npm packages.
Related
I've written this function to try and read a file located in the same directory as my Javascript files and index.html file. I've read from files before, but normally I have the user select the file themselves, so I've never had to create the actual file object.
Does anyone know why the code below doesn't work?
function getFile()
{
var reader=new FileReader();
var file=new File("input.txt");
var str=reader.result;
reader.readAsText(file);
return str;
}
Update:
Some additional information (My apologies if I don't answer your questions, I'm really new to this, and everything I know is self-taught).
Server side or client side? I think this it is going to be hosted serverside - I have a domain that I'm going to upload the file to.
Not possible due to security restrictions. You must use a file that was selected by a user. Imagine what would happen if javascript could read any file on your harddrive - nightmare!
I had a similar code for a desktop app written in JS. It worked well on IE and FF until Chrome came along (yes, it was a very long time ago!) and started restricting the sandbox ever more. At some point, IE and FF also tightened permissions and the method didn't work anymore (I used this code which does not work anymore):
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
file = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(filename);
if (file.exists())
{
inStream = Components.classes["#mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
inStream.init(file, 0x01, 00004, null);
sInStream = Components.classes["#mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
sInStream.init(inStream);
content = sInStream.read(sInStream.available());
}
} catch (ex) {
// and so on...
}
At some point FF and Chrome had some startup flags that enabled the sandbox to be lax on certain security restrictions, but in the end I realized that this is simply old code.
Today, I use localStorage to store data on the local machine. The only disadvantage is that you have to implement an import/export functionality so that it is portable to other browsers/machines by copy/paste the raw text.
What I do is simply this. The maximum size of the database is said to be about 10 MB (but deviations are known to exist) and all I store is a single JSON string:
function store(data)
{
localStorage.data = JSON.stringify(data);
}
function retrieve()
{
return JSON.parse(localStorage.data);
}
Obviously, these two functions are an oversimplification, you need to handle edge cases like when no data exists or a non-JSON string was imported. But I hope you get the idea on how to store local data on modern browsers.
With the File() constructor you can only create new file objects, but cannot read files from lokal disk.
It is not quite clear what exactly you want to achieve.
You say, that the input.txt is located in the same directory as your html and js. Therefore it is located on the server.
If you want to read a file from the server you have to use an ajax request which is already explained in anoter question.
What I use:
Ubuntu 14.04
Node.js 0.10.36
rdflib.js 0.2.0
What I want to achieve:
Parse a html file with RDFa information
Print the found RDF triples
What I have in my Node.js script:
var rdflib = require('rdflib');
var kb = new rdflib.Formula();
rdflib.parse("http://ceur-ws.org/Vol-1085/", kb, "http://www.example.com/", "application/rdfa");
console.log(kb.statements);
The code of rdflib.js calls the third parameter of the 'parse' method 'base', however, I don't know what they mean by that, so I just added dummy URI.
What I get as a result:
[]
Hence, the there are no statements in the store. I would expect to see here the different triples that are present in the html file. Can anybody see what the problem is?
P.S. Because there is no (recent) documentation on how to use rdflib.js, I might be using the above methods in the wrong way.
The first argument of rdflib.parse takes a string that contains the resource at that URI, it doesn't read the URI. You need to use something like request to read the entity body first. Also the URI http://ceur-ws.org/Vol-1085/ does not seem to return application/rdf+xml.
I have an opencart shop. Locally, uploading images work without a glitch. Online, it works only if the image is very small. If I upload an image of, say 300kb, the loading gif next to upload keeps spinning and I get the errors:
ajaxupload.js:
Line 609: if (response) {
Line 610: response = eval("(" + response + ")");
Line 611: } else {
Line 612: response = {};
Line 613: }
Why is this happening?
EDIT:
I did console.log(response) and you were right, what came back was the HTML of the 404 page. But how can it be too big? It works if the image is 100kb but doesn't if it's 130kb.
Why did I get downvoted?
Your Post request is 404ing so the response is not parseable JSON. Looks like your URL has unencoded /s in the query variables. Make sure to use encodeURIComponent() or some other function to make sure your url is properly escaped
From the error I believe that your response is not a valid JSON.
By the way eval is evil so it's much better to use JSON.parse
You can check your JSON here: http://jsonlint.com/
Edit: somebody asked why eval is evil so here are some reasons
it's slower than JSON.parse since it actually starts a compiler
if not done correctly you can end up with XSS attacks
it inherits the execution context and the scope in which its invoked
If you need to support old IE versions you also don't need to use eval(). You could use the excellent JSON library: https://github.com/douglascrockford/JSON-js
This will offer you... JSON.parse support for old IEs.
Try to rewrite the line just before that error.. (don't copy and paste it).. Works sometimes
I'm using JSON.Stringify and JSON.parse everywhere and it works fine with Firefox. It's working no more with IE9 nor does it work in IE8. What can I do?
JSON.stringify starts with a lower-case s. Both stringify and parse are available in IE8+, but only in standards mode.
Prepend your document with <!DOCTYPE html> if you're currently using quirks mode. Also, watch the capitalization of the JavaScript methods you call - all built-in ones start with a lower-case character.
why do you want to depend on the browser having the object instead just include the script file by Douglas Crockford.. You can find the minifed file here: http://www.json.org/js.html
Once imported you dont have to worry abt the method existing in a browser.
For an alternative, in a scenario where you might need to run in strict mode for whatever reason (I have another library that includes "use strict"), you can look here: https://github.com/douglascrockford/JSON-js. I modified this to check first if JSON is undefined, and only generate the function JSON.parse if it is:
if (typeof JSON === "undefined") {
var JSON = {
parse: <insert value of json_parse from library here>
};
}
My issue was application code not working in IE9 (strict mode being used by a participating library, I believe). That solved the problem for me.
the mere issue is, that sending UTF-8 headers will invalidate the JSON (IE doesn't/didn't like that). as the issue is described, that might still apply for IE9... once wrote a how to, a few years ago. adding JSON support to a browser which can parse native JSON is probably not the optimal solution, since it produces useless overhead - only because failing to deliver the JSON in the expected format.
I am trying to obtain the url from the innerHTML of a web page using javascript.
This is what I'm doing:
var goog = newTabBrowser.contentDocument.getElementsByTagName("pre")[0].innerHTML;
alert(goog.responseData.results[0].url);
BUT it wont work :S
I outputted goog (using alert) and copied that into my program as follows:
var goog = {"responseData": {"results":[{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://stackoverflow.com/","url":"http://stackoverflow.com/","visibleUrl":"stackoverflow.com","cacheUrl":"http://www.google.com/search?q\u003dcache:U1GC2GYOToIJ:stackoverflow.com","title":"\u003cb\u003eStack Overflow\u003c/b\u003e","titleNoFormatting":"Stack Overflow","content":"A language-independent collaboratively edited question and answer site for programmers."},{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://en.wikipedia.org/wiki/Stack_overflow","url":"http://en.wikipedia.org/wiki/Stack_overflow","visibleUrl":"en.wikipedia.org","cacheUrl":"http://www.google.com/search?q\u003dcache:mWu8b0BQAmwJ:en.wikipedia.org","title":"\u003cb\u003eStack overflow\u003c/b\u003e - Wikipedia, the free encyclopedia","titleNoFormatting":"Stack overflow - Wikipedia, the free encyclopedia","content":"In software, a \u003cb\u003estack overflow\u003c/b\u003e occurs when too much memory is used on the call \u003cb\u003estack\u003c/b\u003e. In many programming languages the call \u003cb\u003estack\u003c/b\u003e contains a limited amount \u003cb\u003e...\u003c/b\u003e"},{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://blog.stackoverflow.com/","url":"http://blog.stackoverflow.com/","visibleUrl":"blog.stackoverflow.com","cacheUrl":"http://www.google.com/search?q\u003dcache:iqtvg9Ge1c0J:blog.stackoverflow.com","title":"Blog - \u003cb\u003eStack Overflow\u003c/b\u003e","titleNoFormatting":"Blog - Stack Overflow","content":"Apr 12, 2009 \u003cb\u003e...\u003c/b\u003e Apparently some users who really should know better are confused about the way \u003cb\u003eStack Overflow\u003c/b\u003e works. I take this as a sweeping indictment of \u003cb\u003e...\u003c/b\u003e"},{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://support.microsoft.com/kb/145799","url":"http://support.microsoft.com/kb/145799","visibleUrl":"support.microsoft.com","cacheUrl":"","title":"How to Troubleshoot Windows Internal \u003cb\u003eStack Overflow\u003c/b\u003e Error Messages","titleNoFormatting":"How to Troubleshoot Windows Internal Stack Overflow Error Messages","content":"This article lists steps to help you troubleshoot problems with \u003cb\u003estack overflow\u003c/b\u003e errors in Windows. Stacks are reserved memory that programs use to process \u003cb\u003e...\u003c/b\u003e"}],"cursor":{"pages":[{"start":"0","label":1},{"start":"4","label":2},{"start":"8","label":3},{"start":"12","label":4},{"start":"16","label":5},{"start":"20","label":6},{"start":"24","label":7},{"start":"28","label":8}],"estimatedResultCount":"273000","currentPageIndex":0,"moreResultsUrl":"http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003dStack+overflow"}}, "responseDetails": null, "responseStatus": 200};`
and tried
alert(goog.responseData.results[0].url);
and this worked
innerHTML returns a string—not an object structure. You will probably have to use eval or a JSON parsing library (depending on how secure the JSON data is) to convert it from a string into a JavaScript object.
For example, (using the json2.js JSON library):
var googString = newTabBrowser.contentDocument.getElementsByTagName("pre")[0].innerHTML;
var goog = JSON.parse(googString);
// This should give the correct result
alert(goog.responseData.results[0].url);
Steve
Check this out someone has wrote jquery.google plugin I know this plugin to small and it doesn't support paging or like that. I think it will be help you ?
Just check it's source code.
Regards