window.open(url).print() not working in Safari - javascript

I have an issue while printing in the Safari browser. When I use window.open(url) and try to print this newly opened URL, it tries to print a blank page.
As suggested in few other sites, I tried to set a delay of 3000ms. Like,
window.open(url)
setTimeout(print, 3000);
This tries to print the previous window and not the new tab open.
I have tried using window.focus() before printing. It didn't help.

First, the Window object passed in the setTimeout is the one from the original page, so you should do something like
var popup = window.open(url);
popup.onload= function(){
// this now refers to `popup`
this.print()
}
But since you mentioned a Safari issue, I'll note that this seems to only work for normal document page (at least for HTML files) in this browser.
For documents like data:image/..., the Window object returned by window.open() doesn't have any property (at least in bugged Safari 9.1 on 10.9, didn't tried in other versions), hence you can't call the popup.print() method.
One way for it would be to create yourself the page and e.g for an image, append an <img> tag with the desired url as src.
It will depend on what you are trying to print though.
var url = 'data:image/png;base64,...';
// you have to keep a reference of the new Window
var popup = window.open(url);
var tryToPrint = function() {
// we have access to the window methods
if (popup.print) {
// call directly its print method
popup.print()
} else {
// close this one
popup.close();
// open a new blank one
popup = window.open('');
// create an image
var img = popup.document.createElement('img');
// reproduce default Safari's styles
img.setAttribute('style', '-webkit-user-select:none; display:block; margin:auto;');
// once the image has loaded, we can print the page
img.onload = function() {
popup.print()
};
popup.document.body.appendChild(img);
img.src = url;
}
};
// unfortunately, we can't even listen to the load event of the bugged popup
// so come back to an ugly timeout...
setTimeout(tryToPrint, 200);
Live Demo

Related

Close window with JavaScript background script? (Firefox Extension)

I am currently writing a Firefox extension that opens a new window in my background script. When a user clicks a button on a page the background script executes and opens the window.
So far I have:
// content script
downloadMod(linkToOpen); //button clicked
function downloadMod(url) {
// var test = window.open(url, '_blank');
var myPort = browser.runtime.connect({ name: "cac410c4672fff93bf0d3186636d8876de3dfeb6#temporary-addon"});
myPort.postMessage({ greeting: url });
}
In my background script (the script the above code connects too) I have:
//background script
portFromCS.onMessage.addListener(function (m) {
var test = browser.windows.create({
url: m.greeting,
allowScriptsToClose: true,
});
NOTE: all the code works as expected. However, the trouble comes when closing the window.
I have tried variations of self.close(), window.close(). I even created a function to wait 5 seconds to load the newly created window and then close the page to no avail. All of my attempts come back with the error:
Scripts may not close windows that were not opened by script.
I thought this error was supposed to be removed with the allowScriptsToClose flag?
To close a window you created with browser.windows.create, you need to use browser.windows.remove.
So:
let windowId;
browser.windows.create({url: "http://google.be"}).then((data) => {
windowId = data.id;
});
// Sometime later, use windowId to close the window
setTimeout(function(){
browser.windows.remove(windowId);
}, 5000);

IE Context Menu Item In Javascript

I am trying to create an IE Context Menu Item that points to a Javascript html file as described here https://msdn.microsoft.com/en-us/library/bb735853(v=vs.85).aspx#IEAddOnsMenus_topic1
under the "Adding to a context menu" section. I have the Context menu entry listed in HKCU\Software\Microsoft\Internet Explorer\MenuExt
and it points to an html file with javascript in it. Here is the Javascript code I am using.
<script language="JavaScript">
function pausescript(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}
{
var win = window.open("http://www.example.com");
pausescript(2000);
win.close();
}
</script>
I am trying to pop up a window to the url then wait 2 seconds and close the window. It is working but when it closes the pop up window for some reason IE loses focus and any other window besides IE regains focus even though I am forcing the pop up from an IE context menu. How do I make IE get the focus after the pop up window closes?
Your problem is how to set the registry. I use windows 8.1 and I set the registry in this way:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\MenuExt\&Live Search]
#="C:\Usr\StackOverflow\livesearch.htm"
"Contexts"=dword:00000001
All worked fine (your script).
Like you can see the value of Contexts is different from the one described in the guide (instead of 0x10 i used 1).
It's unusefull to say you need to restart the browser.
The FOCUS PROBLEM
After closing the window poup window IE loses the focus.
Like described in MSDN you need to access external.menuArguments property to get the window handler of current ie.
So the javascript code is:
<script language="JavaScript">
function pausescript(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}
{
var win = window.open("http://www.example.com");
pausescript(2000);
win.close();
try {
// access the current browser window
var parentwin = external.menuArguments;
// get the document element
var doc = parentwin.document;
// focus it
doc.body.focus();
} catch(ex) {
alert(ex);
}
}
</script>

Window.open only if the window is not open

I have a link on my site that opens a new window to a page that plays a very long audio file. My current script works fine to open the page and not refresh if the link is clicked multiple times. However, when I have moved to a seperate page on my site and click this link again, it reloads. I am aware that when the parent element changes, I will lose my variable and thus I will need to open the window, overiding the existing content. I am trying to find a solution around that. I would prefer not to use a cookie to achieve this, but I will if required.
My script is as follows:
function OpenWindow(){
if(typeof(winRef) == 'undefined' || winRef.closed){
//create new
winRef = window.open('http://samplesite/page','winPop','sampleListOfOptions');
} else {
//give it focus (in case it got burried)
winRef.focus();
}
}
You should first to call winRef = window.open("", "winPopup") without URL - this will return a window, if it exists, without reloading. And only if winRef is null or empty window, then create new window.
Here is my test code:
var winRef;
function OpenWindow()
{
if(typeof(winRef) == 'undefined' || winRef.closed)
{
//create new
var url = 'http://someurl';
winRef = window.open('', 'winPop', 'sampleListOfOptions');
if(winRef == null || winRef.document.location.href != url)
{
winRef = window.open(url, 'winPop');
}
}
else
{
//give it focus (in case it got burried)
winRef.focus();
}
}
It works.
Thanks to Stan and http://ektaraval.blogspot.ca/2011/05/how-to-set-focus-to-child-window.html
My solution creates a breakout pop-up mp3 player that remains active site wide and only refreshes if the window is not open prior to clicking the link button
function OpenWindow(){
var targetWin = window.open('','winPop', 'sample-options');
if(targetWin.location == 'about:blank'){
//create new
targetWin.location.href = 'http://site/megaplayer';
targetWin.focus();
} else {
//give it focus (in case it got burried)
targetWin.focus();
}
}
Like you said, after navigating away from original page you're losing track of what windows you may have opened.
As far as I can tell, there's no way to "regain" reference to that particular window. You may (using cookies, server side session or whatever) know that window was opened already, but you won't ever have a direct access to it from different page (even on the same domain). This kind of communication between already opened windows may be simulated with help of ajax and server side code, that would serve as agent when sharing some information between two windows. It's not an easy nor clean solution however.

Printing a web page using just url and without opening new window?

<html>
<head>
<script type="text/javascript">
var URL = "http://localhost:8000/foobar/";
var W = window.open(URL); **Note1**
W.window.print();
</script>
</head>
<p> Print ME...............</p>
</html>
I am using this script to print a webpage.
My views render this page and The JS take care all other things.
But I dont want to open new window for that. So, What should I use instead of window.open(URL) so no new window opens. Similarly, I don't want to open new window for print function.So, Whenever I render this page it do all stuff on the same page. No new window, No new tab. How can I achieve this. I google but nothing seems working.
You can do this using a hidden iFrame (I'm using jquery for the example):
function loadOtherPage() {
$("<iframe>") // create a new iframe element
.hide() // make it invisible
.attr("src", "/url/to/page/to/print") // point the iframe to the page you want to print
.appendTo("body"); // add iframe to the DOM to cause it to load the page
}
This will load the page you want to print. To print, you can add javascript code to the print page so that it gets printed after loading:
$(document).ready(function () {
window.print();
});
This will print the page without showing a new window. I've tested this in IE8,9 and Google Chrome, so I'm not sure if this works for Safari or Firefox, though.
There's a nice example on MDN how to do that with a hidden iframe https://developer.mozilla.org/en-US/docs/Printing#Print_an_external_page_without_opening_it
In reference to #andragon's answer. updated on top of it.
You can do this using an iFrame(Not hidden because hidden iFrame prints the blank page in latest versions of browsers. You can hide after the print is triggered)
function loadOtherPage(link) {
$("<iframe class='printpage'>") // create a new iframe element
.attr("src", link) // point the iframe to the page link you want to print
.appendTo("body");
}
This will load the page link you want to print.
On loading the print page link you can call javascript.
$(document).ready(function () {
window.print();
});
window.onafterprint = function () {
$('.printpage', window.parent.document).hide();
}
This will print the page from the same window and onafterprint Event is triggered when a page has started printing, or if the print dialog box has been closed
window.parent.document is to hide the iFrame block on the parent page.
I'm using Asp .net core with razor html as view, in this case I have used window.print() to print the page then used window.onafterprint to back to the page where used want to be redirected.
You can use ViewBag to replace the "/NewSales" URL.
NOTE: window.onafterprint will be called whenever user clicks Cancel/Submit/Print button in that pop-up.
$(document).ready(function () {
window.print();
window.onafterprint = function () {
window.location.href = "/NewSales";
}
});
function CallPrint() {
var prtContent = document.getElementById('main');
var WinPrint = window.open('', '', 'width=800,height=650,scrollbars=1,menuBar=1');
var str = prtContent.innerHTML;
WinPrint.document.write(str);
WinPrint.document.close();
WinPrint.focus();
}
Call this javascript function on Print button click."main" is the id of the div which we have to print without opening into new window.I want to notify that this will print the current page div.
Try and rever in case of any issue.
Thanks,
Gourav

window.close(); not working when page changed or refreshed

I have this little function to open/close a popup player:
function popuponclick(popup)
{
my_window = window.open("folder/player-itself.htm", popup, "width=350,height=150");
}
function closepopup()
{
my_window.close();
}
I call the functions from HTML anchors that are on each page of the site (idea is to have the player stopped/started whenever you want)...now...
it works well until i change the page, or refresh the existing one - and from then the window can't be closed anymore. Any idea where i'm wrong? Tested in FF and IE8, same behavior.
Thanks for your help.
When you reload the original window (or tab), everything about the old one is gone, blasted into the digital void, never to be seen or heard from again. The bits literally disintegrate into nothingness.
Thus, the "my_window" reference you so lovingly saved when the second window was opened is gone for good, and the "my_window" variable in the newly-loaded window contains nothing. It's name is but a mockery of the variable in the now-dead page.
The only way to deal with this situation is for the popup window to periodically check back via "window.opener" to see if its parent page has been rudely replaced by some interloper. If that happens (and the new page is from the same domain), then the popup page can restore the reference to itself in the new page's "my_window" variable.
edit — OK here's a sample. You'd put something like this in the popup page, not the launching pages:
<script>
var checkParent = setInterval(function() {
try {
if (window.opener && ('my_window' in window.opener))
window.opener.my_window = window;
}
catch (_) {
// clear the timer, since we probably won't be able to fix it now
clearInterval(checkParent);
}
}, 100);
</script>
That's probably pretty close.

Categories