Doing popups correctly - javascript

Basically I have a website that offers a help system. When activated this help system triggers a popup in which the help content appears.
As the users then navigates around the site, through the use of a cookie I detect (that I set when the window is first opened and clear when the user closes the window) whether the window is still opened and load new help content for the new page.
As it turns out the only way to load new content into this popup window is to pop open a new page with the same name (so that we don't multiple popups opening everywhere) with the desired content.
This works fine the first time the user triggers the popup, but after that when I try and automatically try and pop open a window, I have problems with most browsers.
Just wondering if anyone has any ideas on how I can get this to work correctly?'
UPDATE
#Rob
Here is that I have:
Page1.html
<html>
<head>
<script type="text/javascript" src="MainPopup.js"></script>
</head>
<body>
<h1>Page 1</h1>
Next
Click
<script type="text/javascript">popupWindowIfCookieSet('Help1.html');</script>
</body>
Page2.html
<html>
<head>
<script type="text/javascript" src="MainPopup.js"></script>
</head>
<body>
<h1>Page 2</h1>
Prev
Click
<script type="text/javascript">popupWindowIfCookieSet('Help2.html');</script>
</body>
</html>
</html>
Help1.html
<html>
<head>
<script type="text/javascript" src="Helper.js"></script>
</head>
<body>
<h1>Help 1</h1>
</body>
</html>
Help2.html
<html>
<head>
<script type="text/javascript" src="Helper.js"></script>
</head>
<body>
<h1>Help 2</h1>
</body>
</html>
MainPopup.js
var windowLocation;
function setHelperWindow(new_windowLocation){
windowLocation = new_windowLocation;
}
function popup(url){
try{
windowLocation.href = url;
} catch(e){
windowLocation = window.open(url, "HelperWindow").location;
}
}
function popupWindowIfCookieSet() {
//Stuffhere
}
function setPopupActiveCookie() {
//Stuffhere
}
Helper.js
(function(){
var failures = 10*60; //Cancel poller after 1 minute without `opener`
var poller = setInterval(function(){
try{
// Attempt to send the current location object to window.opener
window.opener.setHelperWindow(location);
}catch(e){
if(!window.opener && failures-- < 0) clearInterval(poller);
}
}, 100);
})();
Unfortunately this doesn't work. What should happen is that if i pop open the Helper page from Page1, when I then go to Page2.html, the popup window showing the Help1.html content would switch to Help2.html.
Currently its not doing this. Any ideas.

If your whole website is hosted at the same domain, you can use the window.opener property, in conjunction with some adjustments at your page.
Main: Declare a variable windowLocation, and functions setHelperWindow and popup
Main-popup: Open a new window, and store a reference in variable windowLocation
Helper-window: Create a poller, which attempts to invoke the setHelperWindow of the window.opener object. If the window.opener window has closed, the poller will terminate.
Because the windowLocation variable is getting updated all the time (either after using window.open() or by the poller function in the popup), the possibility of getting blocked by a popup blocker is reduced severely.
Note: Both scripts has to be included at each main and helper page:
<script src="filename.js"></script>
Helper.js
(function(){
var failures = 10*60; //Cancel poller after 1 minute without `opener`
var poller = setInterval(function(){
try{
// Attempt to send the current location object to window.opener
window.opener.setHelperWindow(location);
}catch(e){
if(!window.opener && failures-- < 0) clearInterval(poller);
}
}, 100);
})();
MainPopup.js
var windowLocation;
function setHelperWindow(new_windowLocation){
windowLocation = new_windowLocation;
}
function popup(url){
try{
windowLocation.href = url;
} catch(e){
windowLocation = window.open(url, "HelperWindow").location;
}
}
Example: Usage (main)
Click

Specifying a name for the window like you have done should work, e.g.
window.open('help1.html', 'help');
Then, e.g. when page2 loads,
$(function () {
window.open('help2.html', 'help');
});
Bear in mind though that the popup blocker is going to stop this behaviour from working unless you add an exception. E.g. in chrome, options >> under the bonnet >> content settings >> pop-ups >> manage exceptions.
Disclaimer: I'm not a fan of using popups and would use a lightsout box instead for your online help, loading the content via an ajax request.

Related

To auto close a browser window after popping up new email message

I have a simple html that will pop out a new email message for people to send out email.
I need to close a window after the email message popped out. I wish to keep only the email message box.
This is my code, but it's not working:
<html>
<head>
<script type="text/javascript">
function mymessage()
{
location.href = "mailto:abc#com.sg?subject=EmailToEnter";
}
</script>
</head>
<body onload="mymessage()">
<script type='text/javascript'>
settimeout('self.close()',1000);
</script>
</body>
</html>
Try something like this:
function mymessage()
{
var d=document.createElement('A');
d.target='_blank';
d.href='mailto:abc#com.sg?subject=EmailToEnter';
d.click();
}
function closewindow()
{
var d=document.createElement('A');
d.href="javascript:window.open('', '_self', '').close()";
d.click();
}
Or you can use window.open
Also use construction like this
window.setTimeout(function(){closewindow();},1000);
Use this
setTimeout("window.close()", 1000);
BUT
This method is only allowed to be called for windows that were opened by a script using the window.open() method. If the window was not opened by a script, the following error appears in the JavaScript Console: Scripts may not close windows that were not opened by script.
https://developer.mozilla.org/en-US/docs/Web/API/Window.close

How to redirect and return back to same page after a download

I redirected to download page (I used window.location() or window.location.href() or replace()), but after download happens it should again come back to same page. I tried using setTimeout, but in vain. Another thing I dont have a chance to write redirect in download.php.
Is there any solution for this requirement.
Thanks in advance...
Here is my sample code...
<html>
<head>
<meta http-equiv="refresh" content="5; URL=index.php">
<script type="text/javascript" language="JavaScript">
function doSomething(color)
{
//do something nice with params
document.body.style.background = color;
//alert('Hi......');
/*global window */
/*window.location = 'http://all-free-download.com/free-photos/in_love_cosmos_flower_garden_220378_download.html';*/
window.location.href = 'http://all-free-download.com/free-photos/in_love_cosmos_flower_garden_220378_download.html';
/*return false;*/
//header("location:javascript://history.go(-1)");
window.history.back(-1);
window.onload = function() { setTimeout("redirectPage()",3000);
/*return false;*/
window.location.replace("http://google.com");
document.body.style.background = red;
window.setTimeout(redirectPage(), 500);
}
function redirectPage(){
window.location='http://google.com';
}
function download(){
var url = 'http://all-free-download.com/free-photos/in_love_cosmos_flower_garden_220378_download.html';
var htm = '<iframe src="' + url +'" onload="downloadComplete()"></iframe>';
document.getElementById('frameDiv').innerHTML = htm;
}
</script>
</head>
<body>
This page does call a JavaScript function when the page is loaded,
without using the onload() event call.
<script type="text/javascript" language="JavaScript">
doSomething('blue');
</script>
</body>
</html>
You can go back a page (if it was the last page) by doing:
history.back();
Or store the page URL in sessionStorage (or localStorage) and use window.location.href() on the HTML5 web storage variable. If you move through multiple pages.
Although if the page download.php is a completely different page out of your control then there is nothing you can do. Once you leave a page, the code on that page is gone, and you can't do anything on other pages (imagine the security issues if you could). In that case your best best would be to just open the download page in a new tab.

Calling js function from an iframe when user scrolls to the iframe or when the iframe is in viewport

My website provides iframe code which is put in some other websites.
For simplicity lets say my domain i.e the source of the iframe is www.abc.com and my client who uses my iframe code has domain www.xyz.com.
In my iframe website I try to access geoLocation of user using javascript.
When www.xyz.com is browsed on mobile, www.abc.com (in iframe) puts a confirmation box to allow or deny the access for geoLocation.
Now my issue is:-
I want to show the confirmation box only when the iframe is in the viewable area of the browser. And I want to do it without asking my clients to put any more js code in their website. It should all happen from my iframe source.
I tried the following, but visibilityChanged() gets fired only when we change the browser tab or minimize or maximize the browser...
Sample code. a.html
<!DOCTYPE html>
<html>
<head>
<script>
function onLoad() {
console.log('onload:', (document.hidden));
document.addEventListener("webkitvisibilitychange", visibilityChanged);
}
function visibilityChanged() {
console.log('visibilityChanged: ',arguments);
}
</script>
</head>
<body onload="onLoad()">
test
</body>
</html>
b.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<iframe style="border:1px solid red; width:200px;height:200px;" src="a.html"/>
</body>
</html>
The new PageVisibility API, which should be widely supported on mobile, looks much more promising:
Broad support: http://caniuse.com/#feat=pagevisibility
Spec: http://www.w3.org/TR/page-visibility/
Code snippet from the spec (above):
var timer = 0;
var PERIOD_VISIBLE = 1000;
var PERIOD_NOT_VISIBLE = 60000;
function onLoad() {
timer = setInterval(checkEmail, (document.hidden) ? PERIOD_NOT_VISIBLE : PERIOD_VISIBLE);
if(document.addEventListener) document.addEventListener("visibilitychange", visibilityChanged);
}
function visibilityChanged() {
clearTimeout(timer);
timer = setInterval(checkEmail, (document.hidden) ? PERIOD_NOT_VISIBLE : PERIOD_VISIBLE);
}
function checkEmail() {
// Check server for new messages
}

Prevent webpage dialog from spawning new browser window?

I have an open web page dialog. From there, what I'd like to do is when the user clicks on a link, refresh the contents of the dialog with modified query string parameters. The problem I am running into is that rather than refresh the same web page with new parameters, a new browser window pops up.
Here is the page used to open the dialog:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function ShowPopup() {
var popWinFeatures = "dialogWidth: 800px;dialogHeight:600px;center:yes;status:no;scroll:no;resizable:yes;help:no";
window.showModalDialog("webPageDialog.html","PopUpWin",popWinFeatures);
}
</script>
</head>
<body>
Click For Modal
</body>
</html>
and this is the code within the webpage dialog that attempts to refresh the webpage with changed query string parameters:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var queryString = "?ab=123";
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
$('#testLink').attr('href', newURL+queryString);
});
</script>
</head>
<body>
Please Click Me
</body>
</html>
I've also tried using window.open as well as setting window.location. And I've also tried setting window.location.href but the result was the same.
the new browser window displays exactly what I expect. It's just not in the same window.
Thoughts?
Since posting this question, I came up with two possible solutions. In case anyone comes after me and wants to know what I ended up doing, here you go!
The first was just to make the popup non-modal. Removing the modal piece gave me the behavior exactly like I expected it. This didn't work in my situation however for a different reason... It seems that the session cookie was not carried over which in this web app, would cause the log-in page to be displayed before then displaying the correct page. This struck me as odd, but ran out of time to investigate why that was happening.
Second (and this is the solution i ended up going with) was to use an iframe, and display what i needed within the iframe. Definitely not my favorite, but it works!

why html meta refresh redirection doesn't work on the prompt page?

Please kindly consider the following code:
<html>
<head>
<title>This is the from page</title>
</head>
<body>
<script type='text/javascript'>
function redirect(destination)
{
newWindow = window.open(destination, "_blank", "width=790,height=520");
newWindow.document.write("<meta http-equiv='refresh' content='4;url=" + destination + "'>");
newWindow.document.write("<h1>Now redirecting to destination page in 4 seconds...</h1>");
}
redirect("./to.html");
</script>
</body>
Basically I can only see the prompt page with Now redirecting to destination page in 4 seconds... displayed. But it gets stuck in there forever... Firebug tells me that the meta tag does exist in the prompt page.
Any thoughts? Thanks a lot in advance!
function redirect(destination)
{
setTimeout(function(){window.location = destination;},4000);
}
OK, maybe I get what you're doing; you want to show a "redirecting" page while a new page is being loaded. It may be easiest if you create a brand new HTML page that has the sole purpose of doing redirects. The redirect URL could be added to the query string. Here's how you could create that redirect page (we'll assume this is called redirect.html):
<html>
<head>
<script>
// Parse the query string to get the destination URL
var params = {};
var pairs = window.location.search.substring(1).split('&');
for (var i = 0; i < pairs.length; i++) {
var components = pairs[i].split('=');
params[components[0]] = decodeURIComponent(components[1]);
}
setTimeout(function() { window.location = params.redirect; }, 4000);
</script>
</head>
<body>
<h1>Now redirecting to destination page in 4 seconds...</h1>
</body>
</html>
And here's how you'd use it in your host page:
function redirect(destination)
{
window.open(
'redirect.html?redirect=' + encodeURIComponent(destination), "_blank",
"width=790,height=520");
}
redirect("./to.html");
I think the reason your code isn't working is that the browser has already processed the page and its metadata. Assuming that's the case, adding a redirect after the fact won't work. (Someone who knows more about browser internal would need to verify that.)
I'm not sure why you would run this instead of just loading the page, but one approach that should work is to set a javascript timeout to update the popup's location. For example:
<html>
<head>
<title>This is the from page</title>
</head>
<body>
<script type="text/javascript">
function redirect(destination)
{
newWindow = window.open(destination, "_blank", "width=790,height=520");
newWindow.document.write("<h1>Now redirecting to destination page in 4 seconds...</h1>");
setTimeout(function(){ newWindow.location=destination;}, 4000);
}
redirect("./to.html");
</script>
</body>

Categories

Resources