javascript print() method is not working as expected - javascript

I have a simple HTML code to print the page. Below is the code:
<!DOCTYPE html>
<html>
<head>
<script>
function printPage()
{
var w = window.open("http://www.sigmaaldrich.com/catalog/CofADocRequest.do?symbol=209104&LotNo=MKBP0842V&brandTest=SIGMA","_self");
window.focus();
window.print();
}
</script>
</head>
<body >
<input type="button" onclick="printPage()" value="print a div!" />
</body>
</html>
What the code does is, it displays a button, on clicking that button it calls a function. The function uses open() to open a new URL in the same page by using the “_self ” parameter.
As we can see in the code, the print() is being called after the call to open method. But in my browser IE11, the print pop is being shown befor loading the page.
Due to this I am not printing the correct page.
Can anybody help me on this.

The problem is that window refers to the current window, which is the original.
By opening a new window in self you replace the page, this is basically a redirect.
And if you open it via popup and print it as w.print() than you run into cross-origin security error.
You could use iframe to this with a proxy as shown here
How do print specific content inside the iframe
and
here
How do print specific content inside the iframe

Related

Javascript: Issue with window.print

In recent update of browsers, (firefox 95+) Something weired happened.
Scenario:
- user clicks the print button in main page
- user will be redirected to a new page (print page)
- when the page fully loaded, the window.print() function executes
- when the print dialog dismissed, user will be redirected to main page
So for example, I wrote this html code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
test
<script language="javascript">
window.print();
console.log('1');
</script>
</body>
</html>
As this page describes, The window.print() method will block while the print dialog is open. And its true. unless you have more script lines after that.
Opened an issue here and yet, the problem seems unsolved to me.
if you paste
window.print();
console.log('1');
directly into browser console, it works as it intended.
Any advise?
This works for me in current Safari and Chrome. The console log is executed after the print dialog is dismissed.
window.onafterprint = event => {
console.log('after print');
};
window.print();

Using Chrome Developer Tab for realtime html and javascript testing

In Google chrome web browser
about:blank gives an empty page and F12 gives you access to Developer Tab.
Right-clicking a source in Elements gives Edit as Html Option in Developer Tab
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<button id="myBtn">Button</button>
</div>
<div id="demo">
</div>
<script>
document.getElementById("myBtn").addEventListener("click", function () {
document.getElementById("demo").innerHTML = "Hello World";
});
</script>
</body>
</html>
Above is a JavaScript snippet which I copied in. But JavaScript code is not executing. Is this work flow of real time html editing not supported in chrome ?
Your script would ran, if it existed there when the page gets loaded. After the page has loaded, no script tags will just run when edited in.
You could wrap everything inside the script tags into a function and call that I think, however.
One other, but kind of a useless and technical trick that might let you run JavaScript, by editing in elements after the page has loaded, looks something like this:
If you add that in to the loaded page's HTML, the script inside that input-element's onfocus-attribute should run. This, however, is no proper way to do anything other than Cross-Site Scripting (XSS).
You can use a template literal, document.write() at console. At about:blank page press F12, at console enter
var html = `<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<button id="myBtn">Button</button>
</div>
<div id="demo">
</div>
<script>
document.getElementById("myBtn").addEventListener("click", function () {
document.getElementById("demo").innerHTML = "Hello World";
});
</script>
</body>
</html>`;
document.write(html);
then click <button> element.
You can alternatively click Sources -> Snippets, type or paste the above javascript at center window, click right-pointing triangle at right panel to run javascript at Snippets. You can also right-click at Snippets panel to create a new snippet to run.

Javascript print div not working in Safari

I have a Javascript function that prints the contents of two elements in a webpage. It works in Chrome, Firefox and IE but Safari just brings up an empty window and if I select print, it simply prints a blank page.
Here's my code:
var content = "<!doctype html><html><head>";
content += '<link rel="stylesheet" href="/css/normalise.css" type="text/css" />';
content += '<link rel="stylesheet" href="/App_Themes/CS2011/StyleSheet.css" type="text/css" />';
content += "</head><body>";
//Find the div to insert the rest of the html after
var contractToFind = $(divElement).parent().find("div").get(0);
//Insert rest of code
content += contractToFind.innerHTML;
content += "</body></html>";
//Set up print window and print
var printWindow = window.open('', '', params);
printWindow.document.write(content);
printWindow.document.close();
printWindow.focus();
printWindow.print();
//Close the window
printWindow.close();
Is there a way I can modify my code to allow it to render the page properly in Safari so I can print it? Preferably without using additional plugins.
Edit: Thanks Eric but that didn't work for me. Adding a time delay to the print seems to work well although it's not ideal, even a 10ms delay solves the issue. The line I used was:
setTimeout(this.print, 100);
I found a solution to this problem. The problem resides in the fact that window.print() is not standard for all browser and Safari probably takes a different approach on when triggering it.
I changed a little your code so maybe this solution can't fit your possibility but it works for all browser (tested on Safari, FF, Chrome, IE8).
Note that you need to have a different page for the popup content (I changed the code to retrieve the contract to make a sample for myself, hope you will figure out how to get contract content).
The code:
HTML for the page that opens the popup
<body>
<input type="button" id="popup" value="Open Popup" />
<div id="yourContract">
<div>blablabla</div>
<div>blablabla2</div>
<div>blablabla3</div>
<table>
<tr>
<td>blablabla td1</td>
<td>blablabla td2</td>
</tr>
<tr>
<td>blablabla td3</td>
<td>blablabla td4</td>
</tr>
</table>
</div>
</body>
<script>
$("#popup").click(function(){
var win = window.open("static.html");
});
</script>
HTML for the popup (static.html):
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
$.holdReady(true);
$.getScript("print.js", function() {
$.holdReady(false);
});
</script>
</head>
<body>
<script>
var contract = window.opener.$("#yourContract").html(); //change to fit your needs
$("body").html(contract);
</script>
</body>
</html>
JS file (print.js) called by static.html
$(document).ready(function(){
window.print();
window.close();
});
How does it works:
static.html consists of two script section. The section in the body loads via javascript the content in the page.
The section in the head prevent the document to trigger ready status by setting holdReady to true. Then it loads print.js which waits for document to be ready, but we will decide the exact moment because we are preventing it.
After the script is included in the page holdReady is set again to false, triggering the ready status to document and calling the print() and close() functions on the window.
This however occurs after the browser has loaded all the page content, so you will see the preview in the popup page and the print dialog.
Hope this solution is what you need.

Chrome JavaScript console is null after submitting the page

This was unexpected. I use Chrome as my primary development browser and make generous use of "console.log" (way better than alerts!)
Anyway, I have a page inside an IFrame (for uploading images). That page includes scripts that often write out to the console window (console.log) for tracking purposes. The first time the parent page submits the embedded page via script, everything goes smoothly. If I, however, then attempt to submit the page a second time I get the error ...
Uncaught TypeError: Cannot call method 'log' of null
All of a sudden it seems that the console is no longer available. If I replace it with an alert the alert box appears as expected, but the page no longer submits either.
Has anybody experienced anything like this before?
I want to thank folks for their responses. I did not include any code in the OP because it is an extensive script and parsing out an "example" of what I was attempting to do so that it wasn't too tedious to go through would likely strip out any relevancy.
I am posting, however to say that I did discover the problem.
I have PageA which contains an IFrame which is in turn loaded with PageB.
<html>
<head><title>PageA</title></head>
<body>
<IFrame src="PageB" name="frame1" id="frame1"></IFrame>
</body>
</html>
PageB contains a function that needs to be called from PageA when a button is clicked.
<!-- PageB -->
<html>
<head><title>PageB</title></head>
<body>
<form id="form1" name="form1" >
</form>
<script>
var SubmitForm = function(){
var $form = $("form[id$='form1']");
$form[0].submit(); // this was not firing
console.log("some log output"); // this was throwing an error
};
</script>
</body>
</html>
<!-- PageA -->
<html>
<head><title>PageA</title></head>
<body>
<IFrame src="PageB" name="frame1" id="frame1"></IFrame>
<button onclick="submitIFrameForm()">Submit</button>
<script>
var frameWindow = frames["frame1"];
var frameForm = frameWindow.SubmitForm;
function submitIFrameForm(){
frameForm();
};
</script>
</body>
</html>
THE PROBLEM
When PageA first loads, the IFrame is loaded with PageB and the script in PageA makes it's reference (frameForm) to the "SubmItForm()" function on PageB. When I click on the submit form button in PageA, PageB is submitted back to the server. No problem ...
However when PageB is submited it is UNLOADED from the window. So when I click on the
submit button in PageA a second time, although PageB may reload it is a different instance of the page. Therefore all the variables which reference the original PageB are now pointing to nothing ... hence the window that console was referencing no longer exists, so the "log" method cannot run.
THE FIX
Instead of creating a global reference to the contents of the IFrame, we must re-establish this reference to the function each time the button is clicked. (Since the IFrame is a member of PageA we do not need to re-establish the IFrame reference).
<!-- PageA -->
<html>
<head><title>PageA</title></head>
<body>
<IFrame src="PageB" name="frame1" id="frame1"></IFrame>
<button onclick="submitIFrameForm()">Submit</button>
<script>
var frameWindow = frames["frame1"];
function submitIFrameForm(){
frameWindow.SubmitForm(); // move the reference to the click event handler
};
</script>
</body>
</html>
I hope that this made sense and that it helps someone out there. I get caught up on this kind of stuff constantly.

javascript rendered HTML page still loading

I have a mother page, where is jvscrpt function called openWin() , which opens a new window.
Here is my code:
<html>
<head>
<script type="text/javascript">
function openWin()
{
win=window.open();
win.document.write("<html>");
win.document.write("<head>");
win.document.write("<style type=\"text/css\">");
win.document.write("#media print{.input {display:none}}");
win.document.write("</style>");
win.document.write("</head>");
win.document.write("<body>");
win.document.write("<table align=\"center\">");
win.document.write("<tr><td>result:</td><td>100,--€</td></tr>");
win.document.write("<tr><td colspan=\"2\" id=\"idcko\"><input type=\"button\" value=\"click\" class=\"input\" onclick=\"window.print();\"/></td></tr>");
win.document.write("</table>");
win.document.write("</body>");
win.document.write("</html>");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="openWin();" />
</form>
</body>
</html>
When I click on button "Click me!" a new window appears, but browser can`t stop loading the page.The page has full functionality,but for example when I want to see source code in Mozilla, I get only a blank page.
Please help...
call
win.document.close();
At the end(after the last write() )
It signals to the browser that the write-process is finished and the document is complete.
but for example when I want to see
source code in Mozilla, I get only a
blank page.
This is because the source was written by your javascript - this is the same as AJAX (you can't view the changes in the source).
Perhaps you would be better of just opening a new page and pass whatever paramters it needs either via a GET/POST or server-side.

Categories

Resources