SWF Object library will work in all the browsers? - javascript

if (typeof t.plugins != D && typeof t.plugins[S] == r) {
ab = t.plugins[S].description;
if (ab && !(typeof t.mimeTypes != D && t.mimeTypes[q] && !t.mimeTypes[q].enabledPlugin)) {
T = true;
X = false;
ab = ab.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
ag[0] = parseInt(ab.replace(/^(.*)\..*$/, "$1"), 10);
ag[1] = parseInt(ab.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
ag[2] = /[a-zA-Z]/.test(ab) ? parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0
}
} else {
if (typeof O.ActiveXObject != D) {
try {
var ad = new ActiveXObject(W);
if (ad) {
ab = ad.GetVariable("$version");
if (ab) {
X = true;
ab = ab.split(" ")[1].split(",");
ag = [parseInt(ab[0], 10), parseInt(ab[1], 10), parseInt(ab[2], 10)]
}
}
} catch (Z) {}
}
}
return {
w3: aa,
pv: ag,
wk: af,
ie: X,
win: ae,
mac: ac
}
}()
The above code used in swf object library .They checking plugin and ActiveX object written in jquery.Activex will work in IE only.My doubt is whether it will work in all the browsers?if it is yes means ,how its working?

Why shouldn't it work? The check for ActiveX is conditional as well as the access to the ActiveX object catched in case of an error.
So any browser that does not support non-IE behavior (that is, all except IE ;)), will be handled by the else.
BTW: the latest version in the repos has the code a little differently structrued
.... }
else if (typeof win.ActiveXObject != UNDEF) {
try {
var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
if (a) { // a will return null when ActiveX is disabled
d = a.GetVariable("$version");
if (d) {
ie = true; // cascaded feature detection for Internet Explorer
d = d.split(" ")[1].split(",");
playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
catch(e) {}
}
It's not an else anymore but an else if (again with a try-catch). The most common case is coverd before hand. They simply check for all the plugins loaded by the browser as reported by navigator.plugins. Since this is the way to do it, most browsers will never enter the else if part.
To get some information about navigator.plugins, check the MDN docs. This is a browser thing and available in all browsers (except the usual IEs, but the technique from the code above will take care of this). This will always be "plugins". If you try to access it differently e.g. "plugin", you will get an error since it is not defined.
I'm not quite sure what you mean by mentioning jQuery. This is vanilla JS, so there is no jQuery used. We used this library quite often and I can asure you, it is stable and well tested.

Related

addEventlistener function gives error in internet explorer

I have the following code which is used for a mixitup filter, this code regulates the input from an input range and sets it to a checkbox which is checked it works in every browser except for internet explorer (tested in ie11). I think it has something to do with the initial function.
var p = document.getElementById("range"),
res = document.getElementById("output");
p.addEventListener("input", function () {
$("output").html(p.value);
var classes = "";
var minimal = 0;
var maximal = p.value;
$("input[type='range']").attr({'data-filter': "."+ maximal});
$("input[type=checkbox].budget").val('.'+maximal);
$( ".active" ).each(function( index ) {
var thisClass = $(this).attr("data-filter");
if (thisClass == '#mix.activiteiten') {
} else {
if (thisClass != 'undefined') {
classes += thisClass + ',';
}
}
});
if (classes.length > 0) {
var replaced = classes.replace('undefined', '');
var matching = 0;
var arrClasses = replaced.split(",")
}
}, true);
p.addEventListener("change", function() {
var $show = $('#FilterContainer').find('#mix.activiteiten').filter(function(){
var price = Number($(this).attr('data-budget'));
if (classes.length == 0) {
return price >= minimal && price <= maximal;
} else {
for (index = 0; index < arrClasses.length; index++) {
var thisValue = arrClasses[index].replace('.', '');
if ($(this).hasClass(thisValue) && price >= minimal && price <= maximal) {
matching = 1;
return (price >= minimal && price <= maximal);
}
}
}
});
$('#FilterContainer').mixItUp('filter', $show);
}, true);
`
Try this ... by using the jQuery On, you can ensure better response across browsers and versions.
var p = document.getElementById("range"),
res = document.getElementById("output");
$("#range").on("input", function () {
...
}, true);
$("#range").on("change", function() {
...
}, true);
In older IE attachEvent method works instead of addEventListner
see Docs
If you're interested in a cross-browser approach, try creating a function that handles the feature detection for you. Here's one way that might help as a starting point:
function registerEvent( sTargetID, sEventName, fnToBeRun )
{
var oTarget = document.getElementById( sTargetID );
if ( oTarget != null )
{
if ( oTarget.addEventListener ) {
oTarget.addEventListener( sEventName, fnToBeRun, false );
} else {
if ( oTarget.attachEvent )
{
oTarget.attachEvent( sOnEvent, fnToBeRun );
}
}
}
}
Note that this function makes a few assumptions that you may wish to expand in in order to incorporate this into production code, such as error checking, fallback to attribute based event handlers, and so on. Still, it may serve as a proof of concept.
Also, those claiming that IE predominately relies on attachEvent are referring to older versions of IE. Starting with IE9, addEventListener is not only supported, it's recommended for IE. To learn more, see:
How to detect features, rather than browsers
Use feature and behavior detection
IECookbook: Compatibility guidelines and best practices
The IE Blog is a good way to stay up-to-date on the latest news and best practices for IE. (For example, here's the entry talking about why you should use addEventListener instead of attachEvent.)
Hope this helps...
-- Lance
P.S. If 'addEventListener' doesn't seem to be working for you, trying adding <!DOCTYPE html> as the first line of your HTML file. To learn more, see How to enable standards support.
P.P.S. If you create a personal library of such functions, you can greatly reduce the amount of time it takes you to incorporate common tasks into new projects.

JavaScript files.length not working in ie9 need alternative approach

I have the following JavaScript function which is failing in internet explorer 9 on the line which declares the variable filesattached.
function VesselDetails() {
insurancestart = $('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').val();
insuranceend = $('#ctl00_ContentPlaceHolder1_datetimepickerinsend').val();
filesattached = $("input:File")[0].files.length;
//set up JS objects
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').datetimepicker({ format: 'd/m/Y H:i a' });
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').datetimepicker({ format: 'd/m/Y H:i a' });
//subscribe to change events
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').change(function () {
insurancestart = $("ctl00_ContentPlaceHolder1_datetimepickerinsstart").val();
});
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').change(function () {
insuranceend = $("ctl00_ContentPlaceHolder1_datetimepickerinsend").val();
});
$("input:File").change(function () {
filesattached = $("input:File")[0].files.length;
});
ins_client();
}
The ins_client method looks like this:
function ins_client(sender, e) {
if (pagemode == 'EditVessel') {
e.IsValid = true;
}
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && filesattached > 0) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
}
This all works perfectly well in chrome and ie 11 but the length property is returning an undefined for ie 9. I am using the length because I only want the page to be valid for a new vessel request once a document has been submitted, is there another way of doing this which will work in ie 9 onwards and chrome, apologies if this has already been answered elsewhere but I cannot find a workaround anywhere that enables this to continue working in the same way but in ie9 onwards and chrome.
I replaced:
filesattached = $("input:File")[0].files.length;
With:
var areFilesAttached = document.getElementById('ctl00_ContentPlaceHolder1_fuAttachment').value ? true : false;
Within the VesselDetails function.
Then replaced the if statement within ins_client with the following:
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && areFilesAttached == true) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
This was an alternative approach which enabled me to check whether or not a file had been provided without using the files.length property which is not compatible with IE9.
I'm afraid this can't be achieved, IE9 does not support HTML5 File API and therefore it returns undefined value for files property.
Take a look at FILE API

What Chrome does instantly, Firefox takes 30 seconds

Currently, I am creating a program that will turn source code into highlighted HTML-like text. When I tested it, though, I found some strange results. On Chrome, the program will parse 1000 lines of source almost instantaneously. Firefox, however, takes 30 seconds to parse the same 1000 lines. And, ironically enough, IE10 only takes 18 seconds.
Now, I understand that different browsers implement javascript differently and that Chrome tends to be faster, but I do not understand why it is taking Firefox over 30 times longer. I ran a raw while-loop test of 10,000,000,000 operations on each, and it took FF 14 seconds and Chrome 12. Therefore, I am inclined to believe that somewhere in my code is something that takes Firefox an abnormally long time to accomplish; I've done research, but nothing I've found so far would indicate the large discrepancy I am seeing.
So, does anyone have any suggestions as to what may be causing this? I've posted the problem area of the code below (commenting this portion out causes both browsers to parse instantaneously). start and end are both regular expressions; istream is where the source code is coming from, and ostream is where parsed code goes to. istream.read() calls the String slice() method. Finally, this function is called many many times throughout the program.
function(buffer, istream, ostream){
if(start.test(istream.content)){
buffer = istream.read();
ostream.write('[[span class="' + type + '"]]' + buffer);
do{
/* Special Cases */
if(end.test(ostream.content + istream.peek()) && (istream.peek() == "\n" || istream.peek() == " " || istream.peek() == "\t")){
include = true;
break;
}
else if(istream.peek() == "\n"){
istream.read();
ostream.write('[[/span]][[/span]]\n[[span class="line"]][[span class="' + type + '"]]');
continue;
}
else if(istream.peek() == "\t"){
istream.read();
ostream.write("#<    >#");
continue;
}
else if(istream.peek() == " "){
istream.read();
ostream.write("#< >#");
continue;
}
ostream.write(istream.read());
} while(!istream.isEmpty() && !end.test(ostream.content));
if(include || istream.isEmpty())
ostream.write('[[/span]]');
else{
var ending = ostream.content.length-1;
while(!end.test(ostream.content.substr(ending)))
--ending;
istream.content = ostream.content.substr(ending) + istream.content;
ostream.content = ostream.content.substring(0, ending) + '[[/span]]';
}
return true;
}
return false;
}
Any insight would be greatly appreciated, and if you have any queries as to how certain aspects of this are implemented, I will oblige. Thanks in advance.
Definition of istream and ostream objects:
function IOstream(init){
this.content = init;
this.read = function(){
var tmp = this.content.charAt(0);
this.content = this.content.slice(1);
return tmp;
};
this.peek = function(){ return this.content.charAt(0); };
this.write = function(str){ this.content += str; };
this.isEmpty = function(){ return this.content.length == 0; }
}
I think it is because on every .read() call you make content.slice(1) and every time it copies the entire string but first character and can take a lot of time.
Try modifyin your IOStream class like this:
function IOstream(init){
this.content = init;
this.cursor = 0;
this.read = function(){
var tmp = this.content.charAt(this.cursor);
this.cursor++;
return tmp;
};
this.peek = function(){ return this.content.charAt(this.cursor); };
this.write = function(str){ this.content += str; };
this.isEmpty = function(){ return this.cursor>=this.content.length; }
}
I think it will solve your speed problem in all browsers.
Noticed you're using loose equality. I would start there and change the == to === and see if it makes a difference.
Here is a jsperf of loose vs strict: http://jsperf.com/performance-of-loose-vs-strict-equality

How to detect if browser supports HTML5 Local Storage

The following code alerts ls exist in IE7:
if(window.localStorage) {
alert('ls exists');
} else {
alert('ls does not exist');
}
IE7 doesn't really support local storage but this still alerts it does. Perhaps this is because I am using IE9 in IE7 browser and document modes using the IE9 developer tool. Or maybe this is just the wrong way to test if LS is supported. What is the right way?
Also I don't want to use Modernizr since I am using only a few HTML5 features and loading a large script isn't worth it just to detect support for those few things.
You don't have to use modernizr, but you can use their method to detect if localStorage is supported
modernizr at github
test for localStorage
// In FF4, if disabled, window.localStorage should === null.
// Normally, we could not test that directly and need to do a
// `('localStorage' in window) && ` test first because otherwise Firefox will
// throw bugzil.la/365772 if cookies are disabled
// Also in iOS5 & Safari Private Browsing mode, attempting to use localStorage.setItem
// will throw the exception:
// QUOTA_EXCEEDED_ERRROR DOM Exception 22.
// Peculiarly, getItem and removeItem calls do not throw.
// Because we are forced to try/catch this, we'll go aggressive.
// Just FWIW: IE8 Compat mode supports these features completely:
// www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files
Modernizr.addTest('localstorage', function() {
var mod = 'modernizr';
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
});
updated with current source code
if(typeof Storage !== "undefined")
{
// Yes! localStorage and sessionStorage support!
// Some code.....
}
else
{
// Sorry! No web storage support..
}
This function works fine:
function supports_html5_storage(){
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
return false;
}
}
Source: www.diveintohtml5.info
Also I don't want to use Modernizr since I am using only a few HTML5
features and loading a large script isn't worth it just to detect
support for those few things.
To reduce Modernizr file size customize the file at http://modernizr.com/download/ to fit your needs. A localStorage-only version of Modernizr comes in at 1.55KB.
Try window.localStorage!==undefined:
if(window.localStorage!==undefined){
//Do something
}else{
alert('Your browser is outdated!');
}
You can also use typeof window.localStorage!=="undefined", but the statement above already does it
I didn't see it in the answers, but I think it's good to know that you can easily use vanilla JS or jQuery for such simple tests, and while Modernizr helps a lot, there are clean solutions without it.
If you use jQuery, you can do:
var _supportsLocalStorage = !!window.localStorage
&& $.isFunction(localStorage.getItem)
&& $.isFunction(localStorage.setItem)
&& $.isFunction(localStorage.removeItem);
Or, with pure Vanilla JavaScript:
var _supportsLocalStorage = !!window.localStorage
&& typeof localStorage.getItem === 'function'
&& typeof localStorage.setItem === 'function'
&& typeof localStorage.removeItem === 'function';
Then, you would simply do an IF to test the support:
if (_supportsLocalStorage) {
console.log('ls is supported');
alert('ls is supported');
}
So the whole idea is that whenever you need JavaScript features, you would first test the parent object and then the methods your code uses.
Try catch will do the job :
try{
localStorage.setItem("name",name.value);
localStorage.setItem("post",post.value);
}
catch(e){
alert(e.message);
}
Try:
if(typeof window.localStorage != 'undefined') {
}
if (window.localStorage){
alert('localStorage is supported');
window.localStorage.setItem("whatever", "string value");
}
Modifying Andrea's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...
var ls = {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
};
var ls = {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
};
function script(){
if(ls){
alert('Yes');
} else {
alert('No');
}
}
<button onclick="script()">Local Storage Support?</button>
I know I'm a little late to the party, but I have a few useful functions I cooked up and threw into a file named 'manage_storage.js'. I hope they are as useful to you guys, as they have served me well.
Remember: The function you're looking for (that answers this question) is isLclStorageAllowed.
So without further ado here is my code:
/* Conditional Function checks a web browser for 'session storage' support. [BEGIN] */
if (typeof isSessStorageAllowed !== 'function')
{
function isSessStorageAllowed()
{
if (!!window.sessionStorage && typeof sessionStorage.getItem === 'function' && typeof sessionStorage.setItem === 'function' && typeof sessionStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ss_test_itm_key = 'ss_test_itm_' + String(cur_tm);
var ss_test_val = 'ss_test_val_' + String(cur_tm);
sessionStorage.setItem(ss_test_itm_key, String(ss_test_val));
if (sessionStorage.getItem(ss_test_itm_key) == String(ss_test_val))
{
return true;
}
else
{
return false;
};
sessionStorage.removeItem(ss_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'session storage' support. [END] */
/* Conditional Function checks a web browser for 'local storage' support. [BEGIN] */
if (typeof isLclStorageAllowed !== 'function')
{
function isLclStorageAllowed()
{
if (!!window.localStorage && typeof localStorage.getItem === 'function' && typeof localStorage.setItem === 'function' && typeof localStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ls_test_itm_key = 'ls_test_itm_' + String(cur_tm);
var ls_test_val = 'ls_test_val_' + String(cur_tm);
localStorage.setItem(ls_test_itm_key, String(ls_test_val));
if (localStorage.getItem(ls_test_itm_key) == String(ls_test_val))
{
return true;
}
else
{
return false;
};
localStorage.removeItem(ls_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'local storage' support. [END] */
/* Conditional Function checks a web browser for 'web storage' support. [BEGIN] */
/* Prerequisites: 'isSessStorageAllowed()', 'isLclStorageAllowed()' */
if (typeof isWebStorageAllowed !== 'function')
{
function isWebStorageAllowed()
{
if (isSessStorageAllowed() === true && isLclStorageAllowed() === true)
{
return true;
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'web storage' support. [END] */

Browser & version in prototype library?

I am used to using Atlas. Recently i have started transitioning to jQuery and sometimes prototype. The project that i'm currently working on is using prototype.
In Prototype, is there an easy way to get the browser name and version? I've looked over the API documentation and can't seem to find it.
As a completion to nertzy's answer you can add the ability for detecting IE versions using this:
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;
On the other hand you have to detect user agent details on the server side, too.
Anyways browser detection is a seriously flawed strategy for writing cross-browser scripts, that's just to be used when browser feature detection fails. It's pretty easy for a user to alter his/her user agent details.
Prototype offers some flags you can check to get an idea as to which browser is running. Keep in mind that it's much better practice to check for the functionality you wish to use rather than check for a particular browser.
Here is the browser- and feature-detection portion of prototype.js currently in the source tree:
var Prototype = {
Browser: {
IE: !!(window.attachEvent &&
navigator.userAgent.indexOf('Opera') === -1),
Opera: navigator.userAgent.indexOf('Opera') > -1,
WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
Gecko: navigator.userAgent.indexOf('Gecko') > -1 &&
navigator.userAgent.indexOf('KHTML') === -1,
MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
},
BrowserFeatures: {
XPath: !!document.evaluate,
SelectorsAPI: !!document.querySelector,
ElementExtensions: !!window.HTMLElement,
SpecificElementExtensions:
document.createElement('div')['__proto__'] &&
document.createElement('div')['__proto__'] !==
document.createElement('form')['__proto__']
},
}
So you could check if the current browser is IE by investigating the value of Prototype.Browser.IE, or alternatively, be more future-compatible and check for a particular feature like XPath with Prototype.BrowserFeatures.XPath.
You're right - prototype doesn't provide a utility for ascertaining the browser name or version.
If you specifically need to get the browser info as a plugin, I would suggest adding the following (taken from directly jQuery):
var Browser = Class.create({
initialize: function() {
var userAgent = navigator.userAgent.toLowerCase();
this.version = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
this.webkit = /webkit/.test( userAgent );
this.opera = /opera/.test( userAgent );
this.msie = /msie/.test( userAgent ) && !/opera/.test( userAgent );
this.mozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );
}
});
I use this over and above Prototype's browser definitions.
Object.extend(Prototype.Browser, {
ie6: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 6 ? true : false) : false,
ie7: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 7 ? true : false) : false,
ie8: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 8 ? true : false) : false,
ie9: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 9 ? true : false) : false
});
Hope it helps!
I have prototype.js extended after:
var Prototype = { ... };
with this:
// extension
if (Prototype.Browser.IE) {
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
Prototype.BrowserFeatures['Version'] = new Number(RegExp.$1);
}
}
Works fine for me, calling is like:
if (Prototype.Browser.IE && Prototype.BrowserFeatures['Version'] == 8) { ... }
<script type="text/JavaScript">
function getBrowserVersion()
{
var msg = "Not Recognised Browser";
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
{
var ffversion = new Number(RegExp.$1)
for (var i = 1; i < 20; i++)
{
if (ffversion == i)
{
msg = "FF" + i + "x";
break;
}
}
}
else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
{
var ieversion = new Number(RegExp.$1)
for (var i = 1; i < 20; i++)
{
if (ieversion == i)
{
msg = "IE" + i + "x";
break;
}
}
}
alert(msg); // return msg;
}
</script>

Categories

Resources