Javascript Detect if Adobe Reader is installed - javascript

We have some PDF forms that don't display correctly in non-Adobe PDF readers (i.e. WebKit's built-in PDF reader does not properly display some proprietary Adobe things). We want to detect when users don't have Adobe's PDF Reader installed and give them a little warning, but I'm having a hard time figuring out how to do it in 2014.
It seems this script worked in 2011. Basically it loops through navigator.plugins and looks for plugins with the name Adobe Acrobat or Chrome PDF Viewer.
for(key in navigator.plugins) {
var plugin = navigator.plugins[key];
if(plugin.name == "Adobe Acrobat") return plugin;
}
Flash forward to today, Adobe must have changed something, because I have Adobe Acrobat installed, but it doesn't seem to be in navigator.plugins! Where is it now and how do I detect it?

Ok I've updated the script and it's working perfectly fine in all browsers now:
<!DOCTYPE HTML>
<html>
<head>
<title> New Document </title>
<script>
//
// http://thecodeabode.blogspot.com
// #author: Ben Kitzelman
// #license: FreeBSD: (http://opensource.org/licenses/BSD-2-Clause) Do whatever you like with it
// #updated: 03-03-2013
//
var getAcrobatInfo = function() {
var getBrowserName = function() {
return this.name = this.name || function() {
var userAgent = navigator ? navigator.userAgent.toLowerCase() : "other";
if(userAgent.indexOf("chrome") > -1){
return "chrome";
} else if(userAgent.indexOf("safari") > -1){
return "safari";
} else if(userAgent.indexOf("msie") > -1 || navigator.appVersion.indexOf('Trident/') > 0){
return "ie";
} else if(userAgent.indexOf("firefox") > -1){
return "firefox";
} else {
//return "ie";
return userAgent;
}
}();
};
var getActiveXObject = function(name) {
try { return new ActiveXObject(name); } catch(e) {}
};
var getNavigatorPlugin = function(name) {
for(key in navigator.plugins) {
var plugin = navigator.plugins[key];
if(plugin.name == name) return plugin;
}
};
var getPDFPlugin = function() {
return this.plugin = this.plugin || function() {
if(getBrowserName() == 'ie') {
//
// load the activeX control
// AcroPDF.PDF is used by version 7 and later
// PDF.PdfCtrl is used by version 6 and earlier
return getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
} else {
return getNavigatorPlugin('Adobe Acrobat') || getNavigatorPlugin('Chrome PDF Viewer') || getNavigatorPlugin('WebKit built-in PDF');
}
}();
};
var isAcrobatInstalled = function() {
return !!getPDFPlugin();
};
var getAcrobatVersion = function() {
try {
var plugin = getPDFPlugin();
if(getBrowserName() == 'ie') {
var versions = plugin.GetVersions().split(',');
var latest = versions[0].split('=');
return parseFloat(latest[1]);
}
if(plugin.version) return parseInt(plugin.version);
return plugin.name
}
catch(e) {
return null;
}
}
//
// The returned object
//
return {
browser: getBrowserName(),
acrobat: isAcrobatInstalled() ? 'installed' : false,
acrobatVersion: getAcrobatVersion()
};
};
var info = getAcrobatInfo();
alert(info.browser+ " " + info.acrobat + " " + info.acrobatVersion);
</script>
</head>
<body>
</body>
</html>

Related

Autoplay Background HTML5 Sound/Video on Android and iOS

I digg deep into StackOwerflow but not get proper answer from any post.
First here is my code:
(function(a,n){
window.onload = function() {
var b = document.body,
userAgent = navigator.userAgent || navigator.vendor || window.opera,
playSound = function(file) {
var mediaAudio = new Audio(file);
mediaAudio.play();
};
if(b.id == 'fail' || b.id == 'success')
{
if ((/android/gi.test(userAgent) && !window.MSStream))
{
var vm = document.createElement("video"), type;
vm.autoPlay = false;
vm.controls = true;
vm.preload = 'auto';
vm.loop = false;
vm.muted = true;
vm.style.position = 'absolute';
vm.style.top = '-9999%';
vm.style.left = '-9999%';
vm.style.zIndex = '-1';
vm.id = 'video';
if(b.id == 'fail')
type = a;
else
type = n;
for(key in type)
{
if(/video/gi.test(key) && vm.canPlayType(key) == 'probably') {
vm.type = key;
vm.src = type[key];
b.appendChild(vm);
setTimeout(function(){
vm.muted = false;
vm.play();
},100);
return;
}
}
}
else
{
var au = new Audio(),type;
if(b.id == 'fail')
type = a;
else
type = n;
for(key in type)
{
if(/audio/gi.test(key) && au.canPlayType(key) == "probably") {
playSound(type[key]);
return;
}
}
}
}
}
}({
'audio/mpeg':'./sfx/not_ok.mp3',
'audio/wav':'./sfx/not_ok.wav',
'audio/ogg':'./sfx/not_ok.ogg',
'video/mp4; codecs=avc1.42E01E,mp4a.40.2':'./sfx/not_ok.mp4',
},
{
'audio/mpeg':'./sfx/ok.mp3',
'audio/wav':'./sfx/ok.wav',
'audio/ogg':'./sfx/ok.ogg',
'video/mp4; codecs=avc1.42E01E,mp4a.40.2':'./sfx/ok.mp4',
}));
I'm trying to play background sound on all devices on one special page. That page play fail or success sound.
All works great on desktop browsers but when I try to play on mobile, I not get results. In that code you see above, I add one hack where I on android platform generate hidden video and trying to autoplay but not have success.
Is there a way how I can trigger play for video or audio automaticaly?
Is there a way to emulate some click event on body to automaticaly play sound on click event or some other solution?
Thanks!

Javascript For Cross Browser Detection of Incognito Mode (Private Browsing)

I am trying to create a cross browser javascript that detects whether or not the visitor is using Incognito Mode, and gives a alert message if the user visits the page in normal mode.
Currently I have a script, that works just fine on Chrome and Opera, But I need to get it work on all the other browsers as well like firefox, safari, Edge etc.
My script (Working on Chrome and Opera) is:
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
function main() {
var fs = window.RequestFileSystem || window.webkitRequestFileSystem;
if (!fs) {
alert("check failed!");
return;
}
fs(window.TEMPORARY, 100, function(fs) {
alert("You are not using Incognito Mode!");
});
}
main();
}//]]> </script>
Please help me write a single script like this to give the same alert results in all the major web browsers.
Thanks
UPDATE:
I've finally made a working script for Firefox as well. The code is as follows:
<script type='text/javascript'>
var db;
var request = indexedDB.open("MyTestDatabase");
request.onsuccess = function(event) {
if (navigator.userAgent.indexOf("Firefox") != -1)
{
alert("You are not using Incognito Mode!");
};
};</script>
I've used the "if (navigator.userAgent.indexOf("Firefox") != -1)" function so that it executes only on firefox, and not in chrome or any other browser.
UPDATE:
Ok another accomplishment! I've successfully written the script for Safari as well. Here it is:
<script type='text/javascript'>
try { localStorage.test = 2; } catch (e) {
}
if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0)
{
if (localStorage.test = "true") {
alert("You are not using Incognito Mode!");
}
}
</script>
Again, I've used "if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0)" function so that it executes only on Safari, and not in any other browser.
Now I need help in writing script only for Edge browser.
There is this solution I found here:
I just copied it below in case it gets removed.
function retry(isDone, next) {
var current_trial = 0, max_retry = 50, interval = 10, is_timeout = false;
var id = window.setInterval(
function() {
if (isDone()) {
window.clearInterval(id);
next(is_timeout);
}
if (current_trial++ > max_retry) {
window.clearInterval(id);
is_timeout = true;
next(is_timeout);
}
},
10
);
}
function isIE10OrLater(user_agent) {
var ua = user_agent.toLowerCase();
if (ua.indexOf('msie') === 0 && ua.indexOf('trident') === 0) {
return false;
}
var match = /(?:msie|rv:)\s?([\d\.]+)/.exec(ua);
if (match && parseInt(match[1], 10) >= 10) {
return true;
}
return false;
}
function detectPrivateMode(callback) {
var is_private;
if (window.webkitRequestFileSystem) {
window.webkitRequestFileSystem(
window.TEMPORARY, 1,
function() {
is_private = false;
},
function(e) {
console.log(e);
is_private = true;
}
);
} else if (window.indexedDB && /Firefox/.test(window.navigator.userAgent)) {
var db;
try {
db = window.indexedDB.open('test');
} catch(e) {
is_private = true;
}
if (typeof is_private === 'undefined') {
retry(
function isDone() {
return db.readyState === 'done' ? true : false;
},
function next(is_timeout) {
if (!is_timeout) {
is_private = db.result ? false : true;
}
}
);
}
} else if (isIE10OrLater(window.navigator.userAgent)) {
is_private = false;
try {
if (!window.indexedDB) {
is_private = true;
}
} catch (e) {
is_private = true;
}
} else if (window.localStorage && /Safari/.test(window.navigator.userAgent)) {
try {
window.localStorage.setItem('test', 1);
} catch(e) {
is_private = true;
}
if (typeof is_private === 'undefined') {
is_private = false;
window.localStorage.removeItem('test');
}
}
retry(
function isDone() {
return typeof is_private !== 'undefined' ? true : false;
},
function next(is_timeout) {
callback(is_private);
}
);
}

executeScript not work

I have some JS-scripts in my tests. I don't understand why, but it stoped working now.
Maybe it happened after protractor updating (to version 3.3.0).
Maybe somebody know what may happend?
My scripts:
PsComponent.prototype.getHighlightedText = function () {
return browser.executeScript_(function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
});
};
Result:
nothing
And:
PsComponent.prototype.getCaretPosition = function () {
return browser.executeScript(function (input) {
if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
var bookmark = range.getBookmark();
var caret_pos = bookmark.charCodeAt(2) - 2;
} else {
if (input.setSelectionRange){
caret_pos = input.selectionStart;
}
}
return caret_pos;
});
};
Result:
- Failed: JavaScript error (WARNING: The server did not provide any stacktrace information)
Not directly answering the question, but here are the similar functions we are using (I guess things like that would naturally come up in any browser test automation project):
this.getCaretPosition = function (elm) {
return browser.executeScript(function () {
var webElement = arguments[0];
return webElement.value.slice(0, webElement.selectionStart).length;
}, elm.getWebElement())
};
this.getInputSelection = function (elm) {
return browser.executeScript(function () {
var webElement = arguments[0];
return webElement.value.substring(webElement.selectionStart, webElement.selectionEnd);
}, elm.getWebElement())
};
Usage samples:
expect(helpers.getCaretPosition(amountInput)).toEqual(1);
expect(helpers.getInputSelection(amountInput)).toEqual("-100.00");

Nested function not work in Mozilla browser

i have call the below function in my application
function workerCall() {
debugger;
if (typeof (Worker) !== "undefined") {
var worker = new Worker("Scripts/worker.js");
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
worker.postMessage({ 'username': Username });
function workerResultReceiver(e) {
$('.NotificationCount').html(e.data);
if (parseInt(e.data) != 0 && currentPage == "Alert") {
StateFlag = false;
$('.Notification').show();
$('.Drildown').each(function () {
var temp = this.id;
if ($('#' + temp).attr('expand') == "true") {
currentTab = temp;
StateFlag = true;
}
});
currentScrollPosition = $('body').scrollTop();
GetAlerts();
} else {
$('.Notification').hide();
}
}
function workerErrorReceiver(e) {
console.log("there was a problem with the WebWorker within " + e);
}
}
else {
}
}
the method will execute in IE,Chrome but when comes to Mozilla i got an error ReferenceError: workerResultReceiver is not defined.How can i resolve this error?
This happens because you are making reference to function that is not created yet. You need to put this:
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
Above
function workerErrorReceiver
line or at the end of the scope.

Requirejs, Backbonejs browser support function

I need to check whether the browser is supported by my application and I do this the following way:
main.js (main require.js module)
define(['underscore', 'backbone', 'views/mainView', 'views/oldBrowser', 'ui', function(_, Backbone, mainView, oldBrowser){
var _browserHandshaking = function(){
var browserSupportedCookie = $.cookie('browserSupported');
var browserNameCookie = $.cookie('browserName');
var browserVersionCookie = $.cookie('browserVersion');
if(browserSupportedCookie === null){
if(/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
$.ui.browserName = 'chrome';
} else if(/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
$.ui.browserName = 'opera';
/Version[\/\s](\d+\.\d+)/.test(navigator.userAgent);
} else if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
$.ui.browserName = 'ie';
} else if(/Safari[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
$.ui.browserName = 'safari';
/Version[\/\s](\d+\.\d+)/.test(navigator.userAgent);
} else if(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
$.ui.browserName = 'firefox';
} else if(/webOS/i.test(navigator.userAgent)){
$.ui.browserName = 'webos';
} else if(/Android/i.test(navigator.userAgent)){
$.ui.browserName = 'android'
} else if(/iPhone/i.test(navigator.userAgent)){
$.ui.browserName = 'iphone';
} else if(/iPod/i.test(navigator.userAgent)){
$.ui.browserName = 'ipod';
} else if(/BlackBerry/i.test(navigator.userAgent)){
$.ui.browserName = 'blackberry';
}
if($.ui.browserName !== false){
// Set browser version.
if(!$.ui.browserVersion){
$.ui.browserVersion = parseFloat(new Number(RegExp.$1));
}
for(var browserName in $.ui.supportedBrowsers){
if($.ui.browserName === browserName){
if($.ui.browserVersion >= $.ui.supportedBrowsers[browserName]){
$.ui.browserSupported = true;
break;
}
}
}
$.cookie('browserVersion', $.ui.browserVersion, { expires: 7 });
$.cookie('browserName', $.ui.browserName, { expires: 7 });
$.cookie('browserSupported', $.ui.browserSupported, { expires: 7 });
}
} else {
$.ui.browserSupported = browserSupportedCookie;
$.ui.browserName = browserNameCookie;
$.ui.browserVersion = browserVersionCookie;
}
};
_browserHandshaking.call(this);
var Router = Backbone.Router.extend({
routes: {
"old-browser": "oldBrowser",
"*actions": "main",
},
oldBrowser: function(){
oldBrowser.render();
},
main: function(){
mainView.render();
}
});
$.ui.router = new Router();
// Start routing.
Backbone.history.start({
pushState: true,
root: $.ui.rootDir
});
});
Is there a function in Backbone.js that triggers at every action, there I could easily implement this:
preRouting: function(){
if(!$.ui.browserSupported){
return false;
}
return true;
}
I just need to check, if the browser is supported, and if it is supported it can call the mainView, else the oldBrowser view should be triggered, I just don't want to do this at each route function call.
Someone has a better solution for this? And does someone know if it is possible to create a check that is basically a prelimiter for a route function call.
Thanks for help :)
Based on comments, you can check for push state with: (from Can use pushState )
var hasPushstate = !!(window.history && history.pushState);
css3 animations with: ( from Detect css transitions using javascript (and without modernizr)? )
function supportsTransitions() {
var b = document.body || document.documentElement;
var s = b.style;
var p = 'transition';
if(typeof s[p] == 'string') {return true; }
// Tests for vendor specific prop
v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'],
p = p.charAt(0).toUpperCase() + p.substr(1);
for(var i=0; i<v.length; i++) {
if(typeof s[v[i] + p] == 'string') { return true; }
}
return false;
}
var hasCSS3Transitions = supportsTransitions();
There's no need to check the browser name/version if you can simply check to see if the browser has the functionality your application needs.

Categories