ActiveXObject Support in jQuery? How is it Possible - javascript

This is for Non-IE browsers-
I was working on a requirement which needed a XML file to be parsed. After looking at some options, i ended up finding $.parseXML in jQuery.
It worked fine and i can now read the content of the XML from there. But what surprised me was this-
Definition of $.parseXML is-
$.parseXML = function (n){
var r,i;if(!n||"string"!=typeof n)return null;
try{
e.DOMParser
? (i=new DOMParser,r=i.parseFromString(n,"text/xml"))
: (r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))
}catch(o){
r=t
}
return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r}
Now, if you look at the code, the part 'r=new ActiveXObject("Microsoft.XMLDOM")' is what confuses me the most.
Normally, if we try the same thing independently, then the following error is thrown-
ReferenceError: ActiveXObject is not defined
Can someone explain me how is this made possible in jQuery?

The code inside the function definition is meant for IE only.
The ActiveX code is present as a fallback mechanism in case the browser is IE and doesn't support DOMParser(IE9 Supports DOMParser). My guess it that it's still there in case of executing the jquery code in IE8 and below.

Related

Swift JavaScriptCore not working with large files?

https://github.com/gg2001/monero/blob/master/monero/NewWallet.js
I have a js file that is quite large 6000 lines and JavaScript core does not seem to be able to retrieve variable values whereas running the same file in any web browser works fine for me. When I try to retrieve the value of a variable it shows up as undefined, but when I use a js console in a browswer it shows up fine. I am speculating that this is due to the size of the file because when I put
var helloWorld = "Hello World";
in the front of the js file this swift code can retrieve it
func helloWorld() {
if let variableHelloWorld = self.jsContext.objectForKeyedSubscript("helloWorld") {
print(variableHelloWorld.toString())
}
}
but when I put it at the end it cannot.
Normally this indicates a parsing error. Try adding an error handler to self.jsContext before calling objectForKeyedSubscript() and see if it outputs anything insightful.
self.jsContext.exceptionHandler = { context, exception in
print("JS Error: \(exception?.description ?? "unknown error")")
}
Although your JS code may be valid in a browser console, iOS Safari doesn't support as many Javascript features as newer browsers.
I did see a line in your JS source code beginning with just a semicolon (followed immediately by (function). I wonder if the parser might complain about an empty line without a statement..? Maybe nothing, though.

ExternalInterface.call using actionscript "eval" only works in firefox not chrome

Chrome doesn't want to let me access javascript from swf file directly in the URL bar (I know that isn't best practice, but that's what I am trying to accomplish):
Given:
/file.swf?cmd=alert();
With the following code (snippet):
flash.external.ExternalInterface.call("eval", cmd);
This only works in Firefox and not in Chrome. I am taking this approach because in chrome the actionscript 2 way to run JS was to use getURL("Javascript:...., however this doesn't work in Chrome either anymore.
Is there a way around this (by calling the file directly in the browser as opposed to be embedded in a page?)- I have my reasons!
Try creating a custom function the proxies the 'eval' function.
Try this in JS...
function exec_code( $value ) {
window.eval( $value );
}
... and this in AS.
var value:String = "[JavaScript Code to execute]";
if ( ExternalInterface.available ) ExternalInterface.call( 'exec_code', value );

SCRIPT5 : Access is denied on IE-10 after Security Update : jquery-1.4.4.min.js

There was an IE-10 security update on Sept-10. After that, in my application there seems to be an issue accessing a standard div using jquery.
Here is the quick scenario :
I have a jsp layout template where there is a div defined :
<div id="abc"></div>
In that I include a js file k1.js, the following function in that is triggered upon a click of a button
function sample() {
jQuery.get("/fetchmedata.do?a=true", function(data) {
jQuery("#abc").html(data);
});
This was totally functioning across all browsers including ie-10 till Sept -10. After 10th, it still works fine on IE-9 and old IE-10 builds, but on new IE-10 build throws the error in console :
SCRIPT5 : Access is denied
The call stack pointed to internals of Jquery code which I couldn't decipher/understand the context.
The quick fix was to replace the jquery with Javascript, and it worked :
function sample() {
jQuery.get("/fetchmedata.do?a=true", function(data) {
document.getElementById('abc').innerHTML = data;
});
The jquery version was jquery-1.4.4.min.js.
Please advice on what could have been the issue, is it again probably related to not using XDomainRequest instead of XHR, so that we could take precautions in the code to avoid future issues.
Also what is the best practices around it ?
Please advice.

Access native JSON object when JSON2 has overloaded it

I am implementing a bookmarklet which communicates with a iframe through a JSON-RPC protocol.
However some sites, such as cnn.com load JSON2 into window.JSON although the browser already has a native JSON object.
The problem is that within my iframe I would not like to follow the same bad practice, and JSON2 does not seem to be compatible with the native JSON on Mozilla Firefox and Chrome:
So when I run stringify on the native JSON and JSON2, I get the following results:
JSON.stringify({key: "value"})
JSON2
{key:"value"}
Native JSON
{"key":"value"}
(Key is wrapped in ")
The problem is that the native JSON does not like it when the " is missing in the JSON2-produced string and throws an error:
Mozilla Firefox: SyntaxError: JSON.parse: expected property name or '}'
Google Chrome: SyntaxError: Unexpected token k
To solve the problem for good, I need to make sure that I use the same JSON library to encode the string as I do for decoding it.
One way of doing it is to make sure to use JSON2 or JSON3 on both sides, but I'd like to use the native json library where possible.
So now that sites like cnn.com have overriden the native JSON library, how can I get back to it?
I could perhaps create an iframe that points to the same domain and fetch the JSON object from its contentWindow, but that would be highly inefficient.
Isn't there a better way?
not sure if i understand your problem correctly
if you place an empty iframe like this
<iframe id="testFrame" name="testFrame" src="about:blank" style="display:none;"></iframe>
then you can also call from js
testFrame.JSON.stringify(obj);
the only problem is that if you use it in https: src could be javascript:false if you need to support IE6
EDIT: I still think i don't deserve the answer being accepted, so i've come up with a modified version of your code
(function($) {
var frm;
$.getNative = function(objectName, callback) {
if (!frm) {
frm= $("<iframe>", {
src: "javascript:false",
style: "display:none;"
}).appendTo("body").load(function(){
callback(this.contentWindow[objectName]);
// $(this).remove(); <-- this is commented to cache the iframe
});
}
callback(frm[0].contentWindow[objectName]);
}
})(jQuery)
this will enable you to use $.getNative() multiple times in a document without recreating the frame each time.
So far the best solution is to use an iframe, but as Crisim Il Numenoreano has pointed out, it should be pointed to about:blank or javascript:false. This seems to work fine so far:
function getNative(objectName, callback) {
$("<iframe>", {
src: "javascript:false",
style: "display:none;"
}).appendTo("body").load(function(){
callback(this.contentWindow[objectName]);
$(this).remove();
});
}
//Use like this:
getNative("JSON", function(JSON) {
console.log(JSON.stringify({key: "value"}));
});
Note that for bookmarklets jquery must be fetched from reliable sources and protected within a local scope too.

After upgrading to jQuery 1.6.2, globalEval throws an error when trying to execute javascript on page

I upgraded from jQuery 1.4.2 to 1.6.2 and now I get error(in IE). I have JavaScript on the page that gets executed by jQuery globalEval() function
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
In IE the call throws exception:
"Error: Could not complete the operation due to error 80020101."
The data parameter that get executed is javascript variables on page surrounded by <!-- -->
<!--
var id = \"ctrl90900\";
var url = \"myur.com/blah.html\";
-->
I'm using IE9, and jQuery 1.6.2 Not sure why this would cause an error.
If there is any error at all in a script passed to execScript, as far is Internet Explorer is concerned, it will report a 80020101 instead of the original error.
So, also check for missing semicolons and JS features not supported by IE.
For short code passages, i found the most effective debugging technique was to comment out parts of code and see if the error still turns up. If it doesn't, examine the code block that was just commented out for above errors.
It might be the commenting of the code, which is invalid JavaScript and unnecessary in this day and age.
You can strip it out with this regex...
$.globalEval(str.replace(/<!--\s*([\s\S]*?)\s*-->/, '$1'));
jsFiddle.
Just wanted to add a bit to this -- I was getting an error 80020101 whenever in an AJAX-called PHP script that included JavaScript. The script inside the PHP file was also breaking somehow, and refusing to render any of the script in the designated div (other elements of the PHP came through, but nothing inside the JavaScript -- I was trying to draw a chart using HighChart).
Turns out there was an undefined PHP function inside the JavaScript in the included PHP file (used to echo some text). I found this using Firebug.
So bottom line, make sure you don't have any undefined functions inside code coming back via AJAX.

Categories

Resources