I have a page with a "Print" link that takes the user to a printer-friendly page. The client wants a print dialog box to appear automatically when the user arrives at the print-friendly page. How can I do this with javascript?
window.print();
unless you mean a custom looking popup.
You could do
<body onload="window.print()">
...
</body>
I like this, so that you can add whatever fields you want and print it that way.
function printPage() {
var w = window.open();
var headers = $("#headers").html();
var field= $("#field1").html();
var field2= $("#field2").html();
var html = "<!DOCTYPE HTML>";
html += '<html lang="en-us">';
html += '<head><style></style></head>';
html += "<body>";
//check to see if they are null so "undefined" doesnt print on the page. <br>s optional, just to give space
if(headers != null) html += headers + "<br/><br/>";
if(field != null) html += field + "<br/><br/>";
if(field2 != null) html += field2 + "<br/><br/>";
html += "</body>";
w.document.write(html);
w.window.print();
w.document.close();
};
If you just have a link without a click event handler:
Print Page
I do this to make sure they remember to print landscape, which is necessary for a lot of pages on a lot of printers.
Print Me...
or
<body onload="alert('Please be sure to set your printer to Landscape.');window.print();">
etc.
</body>
You can tie it to button or on load of the page.
window.print();
I know the answer has already been provided. But I just wanted to elaborate with regards to doing this in a Blazor app (razor)...
You will need to inject IJSRuntime, in order to perform JSInterop (running javascript functions from C#)
IN YOUR RAZOR PAGE:
#inject IJSRuntime JSRuntime
Once you have that injected, create a button with a click event that calls a C# method:
<MatFAB Icon="#MatIconNames.Print" OnClick="#(async () => await print())"></MatFAB>
(or something more simple if you don't use MatBlazor)
<button #onclick="#(async () => await print())">PRINT</button>
For the C# method:
public async Task print()
{
await JSRuntime.InvokeVoidAsync("printDocument");
}
NOW IN YOUR index.html:
<script>
function printDocument() {
window.print();
}
</script>
Something to note, the reason the onclick events are asynchronous is because IJSRuntime awaits it's calls such as InvokeVoidAsync
PS: If you wanted to message box in asp net core for instance:
await JSRuntime.InvokeAsync<string>("alert", "Hello user, this is the message box");
To have a confirm message box:
bool question = await JSRuntime.InvokeAsync<bool>("confirm", "Are you sure you want to do this?");
if(question == true)
{
//user clicked yes
}
else
{
//user clicked no
}
Hope this helps :)
<script>
const _print = () => {
window.print();
}
</script>
or
<body onload="window.print();"></body>
see the documentation here : https://developer.mozilla.org/en-US/docs/Web/API/Window/print
I know this is an old question, but after fighting with this similar issue, I figured out a way to open a print screen and NOT have to open a new tab, and not have to enable popups.
Hopefully, this helps someone else.
/*
Example:
Print
*/
//LISTEN FOR PRINT URL ITEMS TO BE CLICKED
$(document).off('click.PrintUrl').on('click.PrintUrl', '.print-url', function(e){
//PREVENT OTHER CLICK EVENTS FROM PROPAGATING
e.preventDefault();
//TRY TO ASK THE URL TO TRIGGER A PRINT DIALOGUE BOX
printUrl($(this).attr('href'));
});
//TRIGGER A PRINT DIALOGE BOX FROM A URL
function printUrl(url) {
//CREATE A HIDDEN IFRAME AND APPEND IT TO THE BODY THEN WAIT FOR IT TO LOAD
$('<iframe src="'+url+'"></iframe>').hide().appendTo('body').on('load', function(){
var oldTitle = $(document).attr('title'); //GET THE ORIGINAL DOCUMENT TITLE
var that = $(this); //STORE THIS IFRAME AS A VARIABLE
var title = $(that).contents().find('title').text(); //GET THE IFRAME TITLE
$(that).focus(); //CALL THE IFRAME INTO FOCUS (FOR OLDER BROWSERS)
//SET THE DOCUMENT TITLE FROM THE IFRAME (THIS NAMES THE DOWNLOADED FILE)
if(title && title.length) $(document).attr('title', title);
//TRIGGER THE IFRAME TO CALL THE PRINT
$(that)[0].contentWindow.print();
//LISTEN FOR THE PRINT DIALOGUE BOX TO CLOSE
$(window).off('focus.PrintUrl').on('focus.PrintUrl', function(e){
e.stopPropagation(); //PREVENT OTHER WINDOW FOCUS EVENTS FROM RUNNING
$(that).remove(); //GET RID OF THE IFRAME
if(title && title.length) $(document).attr('title', oldTitle); //RESET THE PAGE TITLE
$(window).off('focus.PrintUrl'); //STOP LISTENING FOR WINDOW FOCUS
});
});
};
if problem:
mywindow.print();
altenative using:
'<scr'+'ipt>print()</scr'+'ipt>'
Full:
$('.print-ticket').click(function(){
var body = $('body').html();
var ticket_area = '<aside class="widget tickets">' + $('.widget.tickets').html() + '</aside>';
$('body').html(ticket_area);
var print_html = '<html lang="tr">' + $('html').html() + '<scr'+'ipt>print()</scr'+'ipt>' + '</html>';
$('body').html(body);
var mywindow = window.open('', 'my div', 'height=600,width=800');
mywindow.document.write(print_html);
mywindow.document.close(); // necessary for IE >= 10'</html>'
mywindow.focus(); // necessary for IE >= 10
//mywindow.print();
mywindow.close();
return true;
});
Related
Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.
I've been printing my page using the code below:
window.print();
An image below is what the print preview in Google chrome browser looks like. It has two main buttons: print and cancel.
I want to know if the user has clicked the print or cancel buttons. What I did uses jquery:
HTML Code of the Print Preview:
<button class="print default" i18n-content="printButton">Print</button>
<button class="cancel" i18n-content="cancel">Cancel</button>
Jquery Code:
$('button > .cancel').click(function (e) {
alert('Cancel');
});
$('button > .print').click(function (e) {
alert('Print');
});
I tried the code above with no luck. What am I missing?
You can not access Chrome's internal windows (printing dialog in this case) directly from a regular web page.
(function () {
var beforePrint = function () {
alert('Functionality to run before printing.');
};
var afterPrint = function () {
alert('Functionality to run after printing');
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
//alert($(mediaQueryList).html());
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
Or, If you want to do something when the print preview gets opened, you can try below:
$(document).bind("keyup keydown", function (e) {
if (e.ctrlKey && e.keyCode == 80) {
setTimeout(function () { CallAfterWindowLoad();}, 5000);
return true;
}
});
function CallAfterWindowLoad()
{
alert("Open and call");
}
Reference:
How to capture the click event on the default print menu called by Javascript window.print()
Maybe if you provide your requirements for this two buttons click event, we can provide you an alternate solution.
it is very easily possible:
<body onafterprint="myFunction()">
The myFunction() that you can define within a tag will be fire when either the printing job is done or the cancel button was pressed.
As far as I know, the print preview is not part of any document your JS can access. These might interest you:
Detecting browser print event
ExtJS 4 - detecting if the user pressed "Print" on the print dialog that was called programatically
<script>
window.print();
onafterprint = function () {
window.location.href = "index.html";
}
</script>
This should do the trick. I've used jQuery v2.2.0 which is included in the html file.
$("#print").click(function() { // calls the id of the button that will print
document.body.style.visibility = 'hidden'; //code for hiding the body
document.getElementById('printthis').style.visibility = 'visible'; // div to be printed
document.getElementById('printthis').style.position = 'absolute'; //some code/css for positioning. you can adjust this
document.getElementById('printthis').style.top = '40px';
document.getElementById('printthis').style.left = '0px';
if (print()) { // shows print preview.
} else { // else statement will check if cancel button is clicked.
document.body.style.visibility = 'visible';
document.getElementById('printthis').style.position = '';
document.getElementById('printthis').style.top = '';
document.getElementById('printthis').style.left = '';
alert("Print Canceled");
}
});
I guess this might as well be used as a way to print certain divs in your html. Just hide the body element and only show the div that you want to print with some positioning css. Hope it works in yours. I've tried it and I can say that it worked for me.
In my WP site I have post content loaded into a div with ajax on a click event.
I need it now to change the url for the current post, would prefer not using hashes.
How would I implement this using my js?
JS:
jQuery(document).ready(function() {
jQuery('#main-content').on('click', '.page a', function(e) {
e.preventDefault();
var url = jQuery(this).attr('href');
jQuery('#main-content').html('<h4>Loading...</h4>').load(url+ ' #main-content');
});
});
I have researched History API but I'm not sure how to implement it with my js.
I haven't done this yet myself, but this should be very simple using the pushState: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
var stateObj = { foo: "bar" };
history.pushState(stateObj, "New Page Title", "newPath.html");
Here's an extended example, where you would replace the content, path, and title with the results from your WordPress query that would grab the next post.
<!doctype html>
<html>
<head>
<title>Push State Testing</title>
<script type='text/javascript'>
var i = 1;
function goToPage( pageNumber, pushState ) {
var content = "Hello World " + pageNumber,
path = "hello_world_" + pageNumber,
title = content,
stateObj = {"content":content}
;
document.title = title;
document.getElementById('content').innerHTML = content;
if( pushState ) {
history.pushState({index:pageNumber}, title, path);
}
i = pageNumber;
}
function nextPage() {
goToPage( i+1, true );
}
window.onload = function() {
goToPage(1);
history.replaceState({index:1}, "Hello World 1", "hello_world_1");
}
window.onpopstate = function(event) {
goToPage(event.state.index, false);
}
</script>
</head>
<body>
<div id='content'>Push State Testing</div>
<button type='button' onclick='nextPage()'>Next</button>
</body>
</html>
In answer to the question in the comments. No, you don't need to know the path of the URL until you know the content. You replace the content and do the pushState at the exact same time:
$('#mainContent').html( contentFromWp );
history.pushState( state, titleFromWp, pathFromWp );
Okay, so to take the above and try to write it for you, which I can't test, so I can't guarantee that this will be working like my above examples...it would be something like this:
jQuery(document).ready(function() {
jQuery('#main-content').on('click', '.page a', function(e) {
e.preventDefault();
var url = jQuery(this).attr('href'),
title = jQuery(this).attr('title')
;
jQuery('#main-content').html('<h4>Loading...</h4>').load(url+ ' #main-content');
document.title = title;
history.pushState({url:url,title:title}, title, url );
});
});
window.onpopstate = function(event) {
document.title = event.state.title;
jQuery('#main-content').html('<h4>Loading...</h4>').load(event.state.url+ ' #main-content');
}
Note the need for onpopstate to make the back button work. You will also want to call a history.replaceState when your webpage first loads like I did in my example so that when users go back to the very first page the first page they were on will reload...otherwise, the user will only be able to go back to the second page they navigated to since going back to the first won't have a stateObj.
Here is my HTML
$html .= " <td><div class='edit_course' data-id='{$id}' data-type='_title' contenteditable='true'>{$obj->title}</div></td>";
Here is my jQuery:
var selector = 'div[contenteditable="true"]';
// initialize the "save" function
$(selector).focus(function(e) {
content_holder = $(this);
content = content_holder.html();
var id = $(this).data('id');
var type = $(this).data('type');
alert( id + type)
// one click outside the editable area saves the content
$('body').one('click', function(e) {
// but not if the content didn't change
if ($(e.target).is(selector) || content == content_holder.html()) {
return;
}
// Edited out AJAX call
});
});
The problem is, when I click on the div, the alert below triggers. When I click outside of the div (after the edit has been made), nothing happens. Can anyone see what is happening?
First click let's user edit content in div. The first click outside, should make ajax call to save.
EDIT: From recommendation below.
Here is new code this works perfectly except it calls the DB every time, all I need is a check to do that only if data is different and I think I got it from there.
Edit2: Final Code
var original_value = '';
$(".edit_course").focus(function(e) {
original_value = $(this).html();
});
// initialize the "save" function
$(".edit_course").blur(function(e) {
var content = $(this).html();
var id = $(this).data('id');
var type = $(this).data('type');
if (content !== original_value) {
// Ajax edited out
}
});
You're not using one() correctly. What you should do is run the AJAX when focus is taken away from the div. Using blur() would probably be your best bet here.
$('body').blur(function(e) {
// your code here...
});
I've seen a lot of posts on communicating from the popup back to parent using window.opener.$('#myDiv').
But once a popup is opened, how does the parent: target and control a div inside the popup?
I'm opening my popup using window.open(url, 'myPopup', 'width=50', 'height=50');
You can adress the parent from the popup like this:
window.opener.foo();
or, on a generic way:
window.opener.property
And, to make sure the parent is still alive:
if (window.opener && !window.opener.closed)
{
// do something
}
On the parent view, you might try:
function add_content(page, text)
{
var texts = page.document.getElementById("content");
texts.innerHTML += text;
}
function start()
{
var popup_page = window.open("popup.htm");
var str = document.getElementById("content").innerHTML;
alert(str);
add_content(popup_page, window.location+" : "+str);
// window.close(); // ?
}