window.print(); does not work in Safari - javascript

The print method does not work on window when using an onclick link Safari. What is the alternative to have a webpage print, in safari via onclick code that is placed on a button? Another odd behavior that's occurring is that when I try and close the window, the print dialog native to the browser then appears.

Try this solution:
try {
// Print for Safari browser
document.execCommand('print', false, null)
} catch {
window.print()
}

I was facing a similar issue with the Safari browser (and not any others).
In my case, aborting all API calls currently in progress immidiately showed the native print dialog.
I'm guessing the reason why your dialog showed up when trying to close the tab/page is that all the network requests are cancelled then.
Here's an example of how to create a pool of ajax requests (when using jQuery):
Stop all active ajax requests in jQuery
Also, to make it work consistently, I had to wrap the $.xhrPool.abortAll function in a short timeout (100ms).
My click handler function (simplified) looks something like this:
function myFunction() {
window.print();
window.setTimeout(function () {
$.xhrPool.abortAll()
}, 100);
}

If you return the result of window.print() to the onclick handler, Safari will not display the print window. I use React and had to make the following change:
//code that does not work:
<button type="button" onClick={() => window.print()}>Print!</button>
//code that does work:
<button type="button" onClick={() => { window.print(); }}>Print!</button>
All other browsers I tested (except Safari on iOS) worked fine either way, such as Chrome on iOS or Chrome for desktop.
My best guess is that as window.print is known to be asynchronous in Safari, perhaps window.print() returns falsy to the onclick handler, which cancels any "popups" from being displayed. This may be why the sample above with the myFunction() code may work when having onclick="window.print()" may not work.

This currently works in Firefox, Chrome and Safari:
try {
if(!document.execCommand('print', false, null)) {
window.print()
}
} catch {
window.print()
}

var frame1 = document.createElement('iframe');
frame1.name = "frame3";
frame1.style.position = "absolute";
frame1.style.top = "-1000000px";
document.body.appendChild(frame1);
var mywindow = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.documentElement ? frame1.contentDocument.documentElement : frame1.contentDocument;
mywindow.document.open();
mywindow.document.write('<html><head><title>' + strTitle + '</title>');
mywindow.document.write('</head><body>');
mywindow.document.write(data);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
setTimeout(function () {
window.frames["frame3"].focus(); // necessary for IE >= 10
window.frames["frame3"].print(); // necessary for IE >= 10
}, 500);
setTimeout(function () {
document.body.removeChild(frame1);
}, 20000);

Have no problem with window.print() with Safari. Sorry I could not try on Windows OS but follow code works for me with MacOS:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button>
Click link
<script>
function myFunction() {
window.print();
}
</script>
</body>
</html>

Related

blur not working in safari

I'm looking to detect clicks in an iframe and based on this answer posted here a while ago (http://jsfiddle.net/oqjgzsm0/), I've got this piece of code working for all browsers except safari 9. For some reason, safari seems to not detect the elem.blur(); and keeps looping the action (in this case, a function call to refresh another iframe). Any ideas on how I can make this solution work for safari as well?
function reload() {
document.getElementById('iframe#2').src += '';
}
var monitor = setInterval(function(){
var elem = document.activeElement;
if(elem && elem.id == 'iframe#1'){
reload();
elem.blur(monitor);
return false;
}
}, 100);

why window.onload not fire in IE

I have some code to open a popup, then resize the it via certain element on the popup page. The following code work fine in Chrome and Firefox, but not IE.
var newWin ;
function openWindow(id) {
newWin = window.open(url,config,setting);
newWin.onload= function () {
newWin.resizeTo(newWin.document.getElementById("certainID").offsetWidth,100);
};
In IE10 a popup will come but the window.load event will never fire.
I also try newWin.$(document).ready , but seems it is invalid.
Any suggestion?
This is an old problem in IE.
One of the best solution is to add new.
Normally we write
window.onload=function() { alert('hello');};
Replace it with
window.onload=new function() { alert('hello');};
Finally I resolve this via setTimeout to check whenever the element in popup is well-generated, then resize the popup window
var newWin ;
function openWindow(id) {
newWin = window.open(url,config,setting);
var resizePopup = function () {
newWin.resizeTo(newWin.document.getElementById("certainID").offsetWidth,100);
newWin.focus();
};
var tryResize = function(){
if(newWin.document.getElementById("certainID")==null){
setTimeout(function(){tryResize();},500);
}
else{
resizePopup();
}
}
tryResize();
};
If using setTimeout, may be popup perform resizing when window not finish loading yet. I think best solution is using setInterval and check whenever document.readyState==='complete" => call clearInterval() and run resize

onmousewheel event not working in firefox

Styling/Headers Lists Blockquotes Code HTML advanced help »
<script>
function event_branding() {
document.getElementById("branding_fade").style.bottom = "0%";
document.getElementById("branding_fade").style.opacity = "1";
document.getElementById("branding_fade").style.transition = "all 2s";
setTimeout(function () { $(".event_branding").css("visibility", "visible")},100);
}
</script>
Try this
<div class="col-xs-7" style="padding-right:3px;">
<img id="train_1_img" class="imageshow_temp" src="http://dummyimage.com/600x400/000/fff"/>
</div>
use this script
var image = document.getElementById("train_1_img");
if (image.addEventListener) {
// IE9, Chrome, Safari, Opera
image.addEventListener("mousewheel", MouseWheelEvent);
// Firefox
image.addEventListener("DOMMouseScroll", MouseWheelEvent);
}
function MouseWheelEvent(e) {
console.log('event', e)
// your statement here...
}
https://jsfiddle.net/fahadsaeed/f8ky3xkq/
Your code is not very clear. Anyways I will put my example here hope it helps
document.getElementById("myDIV").addEventListener("wheel", foo);
function foo() {
console.log("Wheel scrolled")
}
Try it out in JS FIDDLE
I tested and it works in Firefox and Chrome as well
A more detailed work on browser compatibility is explained HERE
This will work.
window.addEventListener('DOMMouseScroll', mouseWheelEvent);
Here is a Jquery example.
http://codepen.io/damianocel/pen/vLerPM
Now, why this is not working for everyone or all browsers is because this is not a standard feature.
Also, MDN says:
On Gecko 17 (Firefox 17) or later, you need to call preventDefault() of wheel events which must be fired for every native event.
On Gecko 16 or earlier, you need to call preventDefault() of MozMousePixelScroll event which must be fired for every native event.
To summarize, browser support is very bad, do not use this for production sites.

onbeforeunload issue with Chrome and Firefox

In last days I noticed that the confirmation alert that I supposed to see before leaving my website page is no more shown on Chrome and Firefox, but it's displayed on IE.
If I debug with Google Chrome Dev Tools, I can see that function confirm is executed, enters the if statement, but no alert box is displayed. I tried to restart Google Chrome and look for an option to reset alert messages, but I didn't find nothing.
Any ideas?
The code is this:
if (window.addEventListener) {
window.addEventListener('beforeunload', confirm, false);
}
else window.attachEvent("onbeforeunload", confirm);
...
function confirm(e) {
if (changed== true) {
return "You haven't saved your changes!";
}
}
I've found a working solution, but actually I don't understand why the attachEvent isn't working anymore. Anyway, this is the working solution, tested on IE, Chrome and Firefox:
I removed the addEventListener and attachEvent lines:
/* if (window.addEventListener) {
window.addEventListener('beforeunload', confirm, false);
}
else window.attachEvent("onbeforeunload", confirm); */
In the HTML, I add the attribute onbeforeunload to the body tag:
<body onbeforeunload="return confirmEvent()">
I also renamed the onbeforeunload function to avoid confusion with the confirm built-in javascript function:
function confirmEvent(e) {
if (changed== true) {
return "You haven't saved your changes!";
}
}
See https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
e.returnValue = confirmationMessage; // Gecko and Trident
return confirmationMessage; // Gecko and WebKit
});
Worked in every Browser i tested ;)
PS: I know its a little bit late

Refresh an element in Javascript

Thanks to Refresh (reload) a page once using jQuery? answer I could solve an issue.
I have a popup window with a checkbox I want to reflect changes from referred main page, almost instantly.
It works great in Safari, Firefox, Chrome, Opera but Internet Explorer.
Thank you
function updateDiv(){
var ord = getCookie('ordinals');
if( ord.indexOf("<?=$ordinal?>")==-1 ){
 document.getElementById("chk<?=$ordinal?>").checked=false//no checked
}
else {
document.getElementById("chk<?=$ordinal?>").checked=true//checked
}
$('chk<?=$ordinal?>').html(newContent);
}
setInterval('updateDiv()', 1000); // that's 1 second
......
......
<body onload="updateDiv(); ....
I think your problem is with:
$('chk<?=$ordinal?>').html(newContent);
Try with this:
var jEl = $('chk<?=$ordinal?>');
jEl.empty();
jEl.append(newContent);

Categories