'onclick' event to open url in new tab or other browser - javascript

I would like to make a button (with a url) dynamic to what the user's browser is using. If the user is using Chrome, then the link will open in a new tab; however if the user is using IE, the link should open in Chrome.
I am unable to make the following code work in Chrome but this works in IE 9.
I have gotten helpful codes from some other posts.
The following will determine/ check which browser the user is on:
function getInternetExplorerVersion()
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
The above snippet works fine.
My code below works seamlessly in IE but not in Chrome.
<input type="button" onclick="openURL()" value="Open Google">
<script>
function openURL()
{
var ver = getInternetExplorerVersion();
var shell = new ActiveXObject("WScript.Shell");
if ( ver = -1 )
shell.run("Chrome www.google.com");
else
window.open('www.google.com','_blank');
}
</script>

Chrome gives an error on that ActiveXObject line, so you should only expose that code to IE. Assuming that ver always gives a number other than -1 in IE you should try this:
function openURL() {
var ver = getInternetExplorerVersion()
if ( ver != -1 ) {
// IE
var shell = new ActiveXObject("WScript.Shell");
shell.run("Chrome www.google.com");
} else {
// other browsers
window.open('//www.google.com','_blank');
}
}
Of course chrome was reading your code, you just didn't see the error. Press F12 to open the browser dev tools and go to the console tab to see script errors.

Related

How to print in chrome on android using jquery since google cloud print is deprecated?

I want to print the page on load in both Windows and Andriod using any browser including google chrome.
I have tried to print on crome in Andriod phone using window.print() but it was giving error,
<script type="text/javascript">
setTimeout(function () {
if (typeof(window.print) != 'undefined') {
window.print();
window.close();
}
}, 1500);
</script>
So I tried some help from google cloud print and what I found is that, it's been deprecated since 31th Dec 2020.
Here is my code for that,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
setTimeout(function () {
if (isAndroid) {
// https://developers.google.com/cloud-print/docs/gadget
var gadget = new cloudprint.Gadget();
gadget.setPrintDocument("url", $('title').html(), window.location.href, "utf-8");
gadget.openPrintDialog();
} else {
if (typeof(window.print) != 'undefined') {
window.print();
window.close();
}
}
}, 1500);
</script>
Can anyone help me in this.
I want to print the URL on load in both Windows and in Andriod.
I implemented as follow:
Added iframe element to page
<iframe id="print-frame" class="print-frame" title="Print" src="https://www.w3schools.com" onload="print"></iframe>
print-frame {display: none}
function print() {
var frame = document.getElementById('print-frame');
if (!frame) return;
var frameWindow = frame.contentWindow;
if (!frameWindow) return;
frameWindow.print();
}
iframe is hidden but onload it opens print dialog. On windows it's enough for printing.
for android I use PaperCut https://www.papercut.com/products/free-software/mobility-print/
Install server part on PC where printers are connected, share printers in admin web UI.
On Android install MobilityPrint app, turn on Print service 'Mobility Print'
then in Chrome browser select Share->Print and select any MobilityPrint service printer

pop up to open pdf does not work on Internet explorer

i use a little java script to open pdf documents in a smaller tab:
// JavaScript Document
function openHeyPopup(objectLink) {
window.open(objectLink, "Externer Link", "width=700,height=600,scrollbars=yes");
}
function initHeyPopup()
{
if (!document.getElementsByTagName){ return; }
var anchors = document.getElementsByTagName("a");
// loop through all anchor tags
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i];
if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "heypopup")){
anchor.onclick = function () {openHeyPopup(this); return false;}
}
}
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function'){
window.onload = func;
} else {
window.onload = function(){
oldonload();
func();
}
}
}
addLoadEvent(initHeyPopup); // run initLightbox onLoad
This works fine for chrome and firefox. But in Internet explorer i get a empty browser window.
http://www.interieursalon.com/wp/wp-content/uploads/2016/08/web-interieursalon-portfolio.pdf
Anybody no how can i fix this for IE?
Best regards
In IE due to security reasons, opening new tabs with insecure content is blocked. we can try out this below code which helps us in downloading the file.
//window.navigator checks for IE version if yes, it gets executed and in place of data give your blob.
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
return window.navigator.msSaveOrOpenBlob(data, "data.pdf");
}

Can't activate an event based on JavaScript IE recognition

I'm trying to add a textarea resizer plugin on my MVC project, but only for IE, since other browsers have a built-in one. In order to do that I have to check if the browser is IE.
I used the JS from this article:
How to detect IE11?
So this is what I use:
function getInternetExplorerVersion() {
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
else if (navigator.appName == 'Netscape') {
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
}
function checkVersion() {
var msg = "You're not using Internet Explorer.";
var rv = getInternetExplorerVersion();
if (rv > -1) {
msg = "You are using IE " + ver;
}
alert(msg);
}
I inserted it in my scripts folder and I access it through this line in Scripts section:
<script type="text/javascript" src="~/Scripts/checkIEVersion.js"></script>
Then I try to implement it on pageload:
<body onload="checkVersion()">
The problem is, nothing happens. I should get an alert, but I get no error, no nothing. When I use only the bottom of the two functions (in the Scripts section with "#(document).ready", it does load correctly.
Could you please assist me?
Thanks in advance!
Turns out I had to include this too:
$(document).ready(function () {
window.onload = function () {
checkVersion();
}
});

Crossbrowser onbeforeunload?

Does window.onbeforeunload() fire in all browsers? I need a onbeforeunload functionality which is supported at least by IE6 and FF3.6.
For IE, onbeforeunload() seems only to be supported by IE9
I found a workaround for Firefox with setTimeout function because it does not have the same behaviour as other web browsers.
window.onbeforeunload = function (e) {
var message = "Are you sure ?";
var firefox = /Firefox[\/\s](\d+)/.test(navigator.userAgent);
if (firefox) {
//Add custom dialog
//Firefox does not accept window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() furthermore
var dialog = document.createElement("div");
document.body.appendChild(dialog);
dialog.id = "dialog";
dialog.style.visibility = "hidden";
dialog.innerHTML = message;
var left = document.body.clientWidth / 2 - dialog.clientWidth / 2;
dialog.style.left = left + "px";
dialog.style.visibility = "visible";
var shadow = document.createElement("div");
document.body.appendChild(shadow);
shadow.id = "shadow";
//tip with setTimeout
setTimeout(function () {
document.body.removeChild(document.getElementById("dialog"));
document.body.removeChild(document.getElementById("shadow"));
}, 0);
}
return message;
}
GitHub: https://github.com/Aelios/crossbrowser-onbeforeunload
No it does not fire in all browsers. It's not supported in mobile browsers e.g. Safari, Opera Mobile & mini, Dolphin. See Is there an alternative method to use onbeforeunload in mobile safari?
Building upon Tushar Ahirrao solution this works cross browser and triggers once (Works in Firefox, Chrome, whatever)
<html>
<head>
<script type="text/javascript">
var app = {};
app.unloaded = false;
app.unload = function() {
if (app.unloaded) return; else app.unloaded = true;
// your code here
return "YO";
};
</script>
</head>
<body onunload="return app.unload();" onbeforeunload="return app.unload();">
YO
</body>
</html>
Paste above template to empty file then edit it
It's my recollection that IE was the only browser to implement onbeforeunload, but some browsers have taken it upon themselves to implement it.
Long story short, IE is about the only browser (with very finite exceptions) you'll find this event consistently in.
Then you can use both like this :
<body onunload="functionName();" onbeforeunload='functionName();' >

Differences in Chrome on various OS

I'm developing a chrome extension and i've met a very strange bug - my code works well on Mac OS, but doesn't work on Windows and Linux versions of Chrome. Versions are the same.
function captureAllScreen() {
chrome.windows.getCurrent(function(w) {
chrome.tabs.captureVisibleTab(w.id, {"format":"png"}, function(response) {
var image = response;
var url;
chrome.tabs.getSelected(w.id, function(response) {
url = response.url;
});
var viewTabUrl = [chrome.extension.getURL('app.html'),
'?id=', id++].join('');
chrome.tabs.create({url: viewTabUrl}, function(tab) {
var targetId = tab.id;
var addSnapshotImageToTab = function(tabId, changedProps, tab) {
if (tabId != targetId || changedProps.status != "complete") {
return;
};
chrome.tabs.onUpdated.removeListener(addSnapshotImageToTab);
var views = chrome.extension.getViews();
for (var i = 0; i < views.length; i++) {
var view = views[i];
if (view.location.href == viewTabUrl) {
view.twm_Draw.sendScreen(image, url); //Application-specific method
break;
}
}
window.close();
};
chrome.tabs.onUpdated.addListener(addSnapshotImageToTab);
});
});
});
};
Update:
What i want to do with this code - is to take a screenshot and tab url and send it to my extension's page. When user clicks on my extension's icon - it opens a popup with two buttons, one of it fires this function.
In Mac Os everything works - this code takes a screenshot, tab url, opens new tab with my application and sends the data there. On Linux & Windows versions of chrome it doesn't send the data, after clicking the icon in the popup you just get a blank tab opened.
I think this part might be causing problems:
var url;
chrome.tabs.getSelected(w.id, function(response) {
url = response.url;
});
//using url
The rest of the code should be wrapped into callback function, otherwise order of execution is not guaranteed.
I'm guess it's only supported on Mac, whatever it does:
view.twm_Draw.sendScreen(image, url); //Application-specific method
I don't know about Unix but on Windows you can only get a screenshot using a NPAPI plugin like the Google extension for screen capture.

Categories

Resources