I'm making a website where I'm opening a new window every 30 seconds. I got it to open the new windows properly, but I would like it to close the last window opened before opening the new one, so only one window is open at a time. How would I do this? Here's my code so far:
<script type="text/javascript">
function open_win() {
window.open("http://www.wol.com");
setTimeout(window.open('http://www.bol.com'),35000);
setTimeout(window.open('http://lol.com'),70000);
setTimeout(window.open('http://col.com'),105000);
}
</script>
You can close a window opened by calling window.close on window.open's return value. So:
<script type="text/javascript">
function open_win() {
var wol,bol,lol;
wol=window.open("http://www.wol.com");
setTimeout(function(){window.close(wol);bol=window.open('http://www.bol.com')},35000);
setTimeout(function(){window.close(bol);lol=window.open('http://lol.com')},70000);
setTimeout(function(){window.close(lol);window.open('http://col.com')},105000);
}
</script>
Here a small interval loop for calling urls. Feel free to add an array for different URLS.
<script type="text/javascript">
var lastWindow = "";
setInterval(function(){
if(lastWindow != ""){ lastWindow.close(); }
lastWindow = window.open("url");
}, 30000);
</script>
You can use a string array to store all of the links, and then iterate through that loop calling open and close after 30 seconds. Using a loop and abstracting open/close allows you to have as many links as you'd like.
var linkArray = ['http://www.wol.com', 'http://www.bol.com', 'http://lol.com', ['http://col.com']
function openWin(link) {
var currentWindow = window.open(link);
setTimeout(currentWindow.close(), 30000);
}
function runLinks() {
for(var i = 0; i< linkArray.length; i++) {
openWin(linkArray[i]);
}
}
Related
Hi this is my hmtl and JS so far what i would like is for it to detect mousemove, scroll and arrows in the iframe windows as well, as most of the website is in iframe i have looked else where and all seems overly complicated to detect movement.
Any help will be appreciated
thank you
<script type="text/javascript">
// Set timeout variables.
var timoutWarning = 1000; // Display warning in 1Mins.
var timoutNow = 2000; // Timeout in 2 mins.
var warningTimer;
var timeoutTimer;
// Start timers.
function StartTimers() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
}
// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(timeoutTimer);
StartTimers();
$("#timeout").dialog('close');
}
// Show idle timeout warning dialog.
function IdleWarning() {
var answer = confirm("Session About To Timeout\n\n You will be automatically logged out.\n Confirm to remain logged in.")
if (answer){
ResetTimers();
}
else{
IdleTimeout();
}
}
// Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
function IdleTimeout() {
window.open(self.location,'_top');
}
</script>
<body onload="StartTimers();" onmousemove="ResetTimers();" onKeyPress="ResetTimers();"
some thing like *
$(".in").on("mouseover",function(){
$(this).css("background","blue");
});
$(".in").on("mouseout",function(){
$(this).css("background","green");
});
.in{width:50px;height:50px;background:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="in"></div>
and use multiple like this $("selector").on("mouseover mouseout mousemove",function(){
call back
});
Here is my website : http://www.brute.adult. And here is the codepen : https://codepen.io/vaninoo/pen/GMbbEg.
As you can see on the website, when you click on links, many pop-ups appear. I've been trying to make them disappear on unload. Here's how the pop ups are called:
$( "#title1" ).click(function() {
popup1 = window.open("protein.html", "_blank","menubar=no,location=no,resizable=no,scrollbars=no,status=yes,top=0,left=500,width=500,height=500");
setTimeout(function(){
var popup2 = window.open("protein2.html", "_blank", "toolbar=no,scrollbars=yes,resizable=yes,top=300,left=100,width=500,height=600");
}, 500);
setTimeout(function(){
var popup3 = window.open("protein3.html", "_blank","toolbar=no,scrollbars=yes,resizable=yes,top=10,left=2000,width=400,height=700");
}, 1000);
setTimeout(function(){
var popup4 = window.open("protein4.html", "_blank", "toolbar=no,scrollbars=yes,resizable=yes,top=50,left=50,width=400,height=400");
}, 1500);
});
As you can see, some of them are delayed to create a rythm in the windows opening. And their var names are popup1, popup2, popup3, popup4 etc.
Now here are the solutions I've tried, with no success:
1) Closing them one by one, but for a reason I can't figure out, this will work only on popup1:
$(window).on('beforeunload', function() {
if(popup1) {
popup1.close();
}
else {}
});
$(window).on('beforeunload', function() {
if(popup2) {
popup2.close();
}
else {}
});
2) Trying to iterate them. I will get, by adding an alert, the names of popup1, popup2 etc. one by one, so the first part of the "while" works. But the "if" doesn't:
$(window).on('beforeunload', function() {
var popup = "popup";
var i = 0;
while (i < 3) {
namesofpopups = popup + i;
i++;
if(namesofpopups) {
namesofpopups.close();
}
}
});
I've been on this for ages, I made it a lot more easy to understand on the codepen. If someone could help it would be immensely appreciated!
Thank you and sorry for the long post!
It's due to the scope of the popup reference variables. You've defined them all (except popup1) inside the click handler, so they are not accessible from the onbeforeunload event handler.
To fix this it would be better to push the references in to an array which you can loop through when the tab is unloaded, something like this:
var popups = [];
$("#title1").click(function() {
popups.push(window.open("protein.html", "_blank", "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,top=0,left=500,width=500,height=500"));
setTimeout(function() {
popups.push(window.open("protein2.html", "_blank", "toolbar=no,scrollbars=yes,resizable=yes,top=300,left=100,width=500,height=600"));
}, 500);
// other popups...
});
$(window).on('beforeunload', function() {
popups.forEach(function(popup) {
popup.close();
});
});
With this being said, bombarding your users with popups is incredibly annoying. In fact, if you did it to me I'd purposefully not use your website. I'd suggest you look in to using modal popups within your page instead, if you really need the behaviour.
I'd like to open a new window, this window has a list of objects, and these objects should be filtered based on a selection from the previous window. I figured I can filter the list through a function, but how do I run said function?
This is what I am able to do:
var popup = window.open('pageURL');
$(popup.document).ready(function() {
// this is where function should be
popup.alert('HelloWorld');
});
But how do I change the alert to a function?
If I have a function on my other app , function test() { alert('HelloWorld'};
How do I run this function from my first app?
Swapping popup.alert('HelloWorld'); with popup.test(); did not work.
You need the reference to the window opened to call functions in the new window, like:
var oNewWindow = window.open("new.window.url", "mywindow");
oNewWindow.onload = function(){oNewWindow.window.newWindowFunction();};
I ended up with this solution
var popup = window.open('http://s234-0057/actiontracker/SiteAssets/Avvik/html/app.aspx');
var readyStateCheckInterval = setInterval(function() {
if (popup.document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
popup.test();
}
}, 50);
Where I check if the popup window is ready, and when it is, cancel check and run function. Solution is from top answer on this question, by #this.lau_
You can write it like this:
function myFunction(){
alert('HelloWorld');
}
var popup = window.open('pageURL');
$(popup.document).ready(function() {
popup.eval(myFunction + "");
popup.myFunction();
});
myFunction in file that contains this code will run in page with pageURL address.
How can I close modal dialog(s) from main page after some time, or when session expires, using JavaScript or jQuery?
Dialog is opened using the following code :
var result = window.showModalDialog("test.aspx" ... );
Dialog must be closed when counter expires like this:
function Discount() {
leftSeconds = leftSeconds - 1;
try { document.getElementById('tbLeft').value = leftSeconds; } catch (ex) { }
if (leftSeconds <= 5) {
clearTimeout(t);
// code for closing modal dialog(s)
} else {
t = setTimeout("Discount()", 1000);
}
}
Modal dialog can be closed from himself, but it's not solution in my case.
While the modal dialog is open, javascript execution on the main page is stopped, because it is waiting for a return value (even though you may not want to return one, or do anything with what it returns).
You can check this with this little example. When you click the button, the page opens, and the timer stops updating. When you close the page, execution is resumed:
<!DOCTYPE html>
<html>
<head>
<script>
var t = 0;
function count() {
document.getElementById('div').innerHTML = ++t;
}
var timer = setInterval(count, 1000);
</script>
</head>
<body>
<div id='div'></div>
<button onclick="window.showModalDialog('http://www.google.es');">Open window</button>
</body>
</html>
So, if you want to close the window automatically, you need to do it from the new document itself. My advice? Implement your timer in the window.load event of your modal page, so it can close itself after the desired time.
window.onload = function() {
setTimeout(function() { window.close(); }, 60000); //close window after 1 minute.
};
I would like to implement a JavaScript code which states this:
if the page is loaded completely, refresh the page immediately, but only once.
I'm stuck at the "only once":
window.onload = function () {window.location.reload()}
this gives a loop without the "only once". jQuery is loaded if this helps.
I'd say use hash, like this:
window.onload = function() {
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
When I meet this problem, I search to here but most of answers are trying to modify existing url. Here is another answer which works for me using localStorage.
<script type='text/javascript'>
(function()
{
if( window.localStorage )
{
if( !localStorage.getItem('firstLoad') )
{
localStorage['firstLoad'] = true;
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
</script>
<script type="text/javascript">
$(document).ready(function(){
//Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1){
// Set the URL to whatever it was plus "#".
url = document.URL+"#";
location = "#";
//Reload the page
location.reload(true);
}
});
</script>
Due to the if condition the page will reload only once.I faced this problem too and when I search ,I found this nice solution.
This works for me fine.
Check this Link it contains a java-script code that you can use to refresh your page only once
http://www.hotscripts.com/forums/javascript/4460-how-do-i-have-page-automatically-refesh-only-once.html
There are more than one way to refresh your page:
solution1:
To refresh a page once each time it opens use:
<head>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
</head>
sollution2:
<script language=" JavaScript" >
<!--
function LoadOnce()
{
window.location.reload();
}
//-->
</script>
Then change your to say
<Body onLoad=" LoadOnce()" >
solution3:
response.setIntHeader("Refresh", 1);
But this solution will refresh the page more than one time depend on the time you specifying
I hope that will help you
<script>
function reloadIt() {
if (window.location.href.substr(-2) !== "?r") {
window.location = window.location.href + "?r";
}
}
setTimeout('reloadIt()', 1000)();
</script>
this works perfectly
Finally, I got a solution for reloading page once after two months research.
It works fine on my clientside JS project.
I wrote a function that below reloading page only once.
1) First getting browser domloading time
2) Get current timestamp
3) Browser domloading time + 10 seconds
4) If Browser domloading time + 10 seconds bigger than current now timestamp then page is able to be refreshed via "reloadPage();"
But if it's not bigger than 10 seconds that means page is just reloaded thus It will not be reloaded repeatedly.
5) Therefore if you call "reloadPage();" function in somewhere in your js file page will only be reloaded once.
Hope that helps somebody
// Reload Page Function //
function reloadPage() {
var currentDocumentTimestamp = new Date(performance.timing.domLoading).getTime();
// Current Time //
var now = Date.now();
// Total Process Lenght as Minutes //
var tenSec = 10 * 1000;
// End Time of Process //
var plusTenSec = currentDocumentTimestamp + tenSec;
if (now > plusTenSec) {
location.reload();
}
}
// You can call it in somewhere //
reloadPage();
i put this inside my head tags of the page i want a single reload on:
<?php if(!isset($_GET['mc'])) {
echo '<meta http-equiv="refresh" content= "0;URL=?mc=mobile" />';
} ?>
the value "mc" can be set to whatever you want, but both must match in the 2 lines. and the "=mobile" can be "=anythingyouwant" it just needs a value to stop the refresh.
Use window.localStorage... like this:
var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
if (refresh===null){
window.location.reload();
window.localStorage.setItem('refresh', "1");
}
It works for me.
After </body> tag:
<script type="text/javascript">
if (location.href.indexOf('reload')==-1)
{
location.href=location.href+'?reload';
}
</script>
You can make one verable once = false then reload your page with if else like if once == false reload page an make once true.
You'd need to use either GET or POST information. GET would be simplest. Your JS would check the URL, if a certain param wasn't found, it wouldn't just refresh the page, but rather send the user to a "different" url, which would be the same URL but with the GET parameter in it.
For example:
http://example.com -->will refresh
http://example.com?refresh=no -->won't refresh
If you don't want the messy URL, then I'd include some PHP right at the beginning of the body that echos a hidden value that essentitally says whether the necessary POST param for not refreshing the page was included in the initial page request. Right after that, you'd include some JS to check that value and refresh the page WITH that POST information if necessary.
Try with this
var element = document.getElementById('position');
element.scrollIntoView(true);`
Please try with the code below
var windowWidth = $(window).width();
$(window).resize(function() {
if(windowWidth != $(window).width()){
location.reload();
return;
}
});
Here is another solution with setTimeout, not perfect, but it works:
It requires a parameter in the current url, so just image the current url looks like this:
www.google.com?time=1
The following code make the page reload just once:
// Reload Page Function //
// get the time parameter //
let parameter = new URLSearchParams(window.location.search);
let time = parameter.get("time");
console.log(time)//1
let timeId;
if (time == 1) {
// reload the page after 0 ms //
timeId = setTimeout(() => {
window.location.reload();//
}, 0);
// change the time parameter to 0 //
let currentUrl = new URL(window.location.href);
let param = new URLSearchParams(currentUrl.search);
param.set("time", 0);
// replace the time parameter in url to 0; now it is 0 not 1 //
window.history.replaceState({}, "", `${currentUrl.pathname}?${param}`);
// cancel the setTimeout function after 0 ms //
let currentTime = Date.now();
if (Date.now() - currentTime > 0) {
clearTimeout(timeId);
}
}
The accepted answer uses the least amount of code and is easy to understand. I just provided another solution to this.
Hope this helps others.
React Hook worked for me.
import { useEffect, useState } from 'react';
const [load, setLoad] = useState(false);
window.onload = function pageLoad() {
if (load) {
window.location.reload(true);
setLoad(false);
}
};
nothing work for me perfectly except this, -added to my JavaScript file-:
function LoadOnce() {
if (localStorage.getItem('executed') == 'false') {
window.location.reload()
localStorage.setItem('executed', true)
}
}
setTimeout(function () {
LoadOnce()
}, 100)
and in the previous page I wrote:
localStorage.setItem('executed', false)
I got the Answer from here and modified it.This is the perfect solution for me.
var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
setTimeout(function() {
if (refresh===null){
window.location.reload();
window.localStorage.setItem('refresh', "1");
}
}, 1500); // 1500 milliseconds = 1.5 seconds
setTimeout(function() {
localStorage.removeItem('refresh')
}, 1700); // 1700 milliseconds = 1.7 seconds
var foo = true;
if (foo){
window.location.reload(true);
foo = false;
}
use this
<body onload = "if (location.search.length < 1){window.location.reload()}">
Use rel="external"
like below is the example
<li>Home</li>