userscript to regularly open and close a window - javascript

I write a simple userscript because I need to log in again when I do not operate some sites for a long time.
But now the script is not what I expected. I wanted to regularly open and then close a window after clicking "startrefresh".
(function() {
'use strict';
const CustomInterval=1000*60*6;
function loop(){
setTimeout(function() {
var RefreshTimeWindow=window.open(window.location.href);
setTimeout(() => RefreshTimeWindow.close(),3000);
loop();
}, CustomInterval);
}
var startrefresh=document.createElement("div");
startrefresh.id="startrefresh";
startrefresh.innerHTML=`<a id='start' href='javascript:void(0);'>---startrefresh---</a>`;
startrefresh.style="z-index:9999; width:200px; height:50px; position:fixed; right:150px; top:200px; display:block; background-color:#FFFF9E; font-size:24px;";
document.body.appendChild(startrefresh);
document.getElementById ("start").addEventListener ("click", loop, false);
})();
It seems that settimeout will be ineffective when I switch to another page in the same tab.
The browser will also block the popup. How can I do it without disabling popup blocking?
How to improve it?

Related

why window.onload not fire in IE

I have some code to open a popup, then resize the it via certain element on the popup page. The following code work fine in Chrome and Firefox, but not IE.
var newWin ;
function openWindow(id) {
newWin = window.open(url,config,setting);
newWin.onload= function () {
newWin.resizeTo(newWin.document.getElementById("certainID").offsetWidth,100);
};
In IE10 a popup will come but the window.load event will never fire.
I also try newWin.$(document).ready , but seems it is invalid.
Any suggestion?
This is an old problem in IE.
One of the best solution is to add new.
Normally we write
window.onload=function() { alert('hello');};
Replace it with
window.onload=new function() { alert('hello');};
Finally I resolve this via setTimeout to check whenever the element in popup is well-generated, then resize the popup window
var newWin ;
function openWindow(id) {
newWin = window.open(url,config,setting);
var resizePopup = function () {
newWin.resizeTo(newWin.document.getElementById("certainID").offsetWidth,100);
newWin.focus();
};
var tryResize = function(){
if(newWin.document.getElementById("certainID")==null){
setTimeout(function(){tryResize();},500);
}
else{
resizePopup();
}
}
tryResize();
};
If using setTimeout, may be popup perform resizing when window not finish loading yet. I think best solution is using setInterval and check whenever document.readyState==='complete" => call clearInterval() and run resize

Javascript -- wait for user interaction without freezing the browser

I don't speak English very well.
My company has developed a web application for internet explorer that very strenuously uses the function showModalDialog and waits for the result.
We are planning to extend the use of the application to other browsers (Firefox, Chrome), and I need to replace "showModalDialog logic" with a logic that will work well on all browsers.
I originally tried using an ajaxcontroltoolkit modalpopup with an iframe inside.
My problem is that, after I have showed the modalpopup, I cannot wait for the user to close the popup window without freezing the web interface.
function OpenDialog() {
var result = window.showModalDialog("page1.html", "input_parameter", "width:100px; height:100px");
//When the popup went closed
alert("result: " + result);
}
//Override showModalDialog function for compatibility with other browser
function myShowModalDialog(url, pars, options) {
//show a jquery modalpopup or ajaxcontroltoolkit modalpopup with an iframe ....
iframe.src = url;
//I need to wait here until the modal popup closed
//HOW?
//get the value from popup
var res = ???????;
return res;
}
window.showModalDialog = myShowModalDialog;
I cannot change the logic for every page in the webapp.
I searched for a method to override the showModalDialog function and recreate the same logic (wait until the popup is closed and get the result that the popup provides for the caller).
Any ideas? Thanks to all
You've discovered the reason why JavaScript relies heavily on asynchronicity, event handlers, and callback functions.
The best solution would be to restructure your code so that your events trigger on event handlers, using jQuery or somesuch to bind the event handlers to the event. Alternatively, you could always use a function in a timeout loop to check periodically if the modal is closed yet, and execute the continuation of your code when it is. That's pretty hacky though, and I don't recommend it. In general, trying to force asynchronous code to fit a synchronous model gets really messy.
Unless I'm not following you, what you need is a callback when the user closes the dialog, right?
Whatever method is executed when the user closes the dialog, monkey patch it to call your function. (A monkey patch is code that adds functionality to existing code, but keeps the old code also).
So if your close method/function looks like:
myCloseDialog = function(){
// do important closing stuff
}
Then you can monkey patch like so:
myNewCloseDialog = function(){
// do important callback stuff, or call your callback function
myCloseDialog(arguments);
}
By the way, your English is very fine :)
I've created a short demo of my suggestion in the comment:
<!DOCTYPE html>
<html>
<head>
<title>modal overlay</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.overlay
{
background-color: rgba(0, 0, 0, 0.1);
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index: 100;
margin:0;
display:none;
}
.box
{
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
width:400px;
height:300px;
background:white;
margin:auto;
padding:10px;
}
</style>
<!--
prepare a style to show/hide overlay and
prevent lost focus when clicking outside the box
-->
<template id="template1">
<style id="style-modal">
*
{ pointer-events: none;
}
.overlay *
{pointer-events: auto;
}
.overlay
{ display:block!important;
}
</style>
</template>
</head>
<body>
<input id="some-input1" type="text">
<button class="modal-open" type="button">open modal dialog</button>
<div id="overlay1" class="overlay">
<div class="box">
<input id="modal-input1" type="text">
<button type="button" class="modal-close">close</button>
</div>
</div>
<script>
document.addEventListener
( 'DOMContentLoaded',
function(ev)
{
var
template1 = document.getElementById('template1'),
styleModal = template1.content.getElementById('style-modal'),
overlay1 = document.getElementById('overlay1'),
box = overlay1.querySelector('.box'),
head = document.querySelector('head')
;
//TODO: could iterate over querySelectorAll
document.querySelector('button.modal-open').addEventListener
( 'click',
function(ev) { head.appendChild(styleModal); },
false
)
overlay1.querySelector('button.modal-close').addEventListener
( 'click',
function(ev)
{ template1.content.appendChild(styleModal);
document.dispatchEvent(new CustomEvent('closemodal', {detail:{relatedTarget:box}}));
},
false
)
},
false
);
document.addEventListener
( 'closemodal',
function(ev){ alert(ev.detail.relatedTarget.querySelector('input').value); },
false
);
</script>
</body>
</html>
Note that this example makes use of <template> element which isn't implemented by IE yet. You can easily generate the style-element in the script, hold it in a variable and add/remove it to/from the head.
Have a look at my showModalDialog polyfill using a modal element and ECMAScript 6 generators, so it does not need an explicit callback function. Statements after showModalDialog() will run after closing the modal.

Gray and disable out the parent window as soon as pop up window is opened

I am trying to disable the Parent window as soon as the child window is opened. I would like to gray out the parent window whenever pop window is opened.
Below is my popup window code-
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var variable1 = getUrlVars()["parameter1"];
var myScript = document.createElement('script');
myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin#domain.net');
document.body.appendChild(myScript);
</script>
<input name="Apply" type="button" id="Apply" value="Apply" ONCLICK="window.location.href='some_url'">
</body>
</html>
Below is my Parent window code-
<html>
<body>
<SCRIPT LANGUAGE="JavaScript">
<!--
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=550,height=650,left = 570,top = 300');");
}
</script>
<input type=button value="Apply" onClick="javascript:popUp('popup_window_url')">
</body>
</html>
What's the best and easy way to disable the parent window here? Any example with my above code will help me a lot in understanding a simple example.
I saw various other post on the stackoverflow but I am not able to understand how to incorporate those things here in my code. I am trying to do something like this.
Any suggestions will be of great help.
Updated fiddle from answer in this question with iframe support http://jsfiddle.net/LT5JC/
Open function is rather simple
function open(url) {
$('#block').fadeIn(); // show grayed pane
$('#iframe').attr('src', url); // update src of iframe
$('#container').fadeIn(); // show container with iframe
}
The example you gave doesn't use a popup in the sense of a new browser window, but a div on the existing page onto which the new content is loaded. This method is possible, as you would use an Ajax call to populate your popup. By using an Ajax call to the second page, you are able to tell when the request has finished, and fade the background out as required. If you really want to, you could use an iFrame, and check when that's loaded, but in my opinion this method isn't as nice.
A simple implementation using jQuery:
var cover = $("<div id='cover'></div>");
var content = $("#content"),
popup_window = $("#popup-window"),
popup_launcher = $("#popup-launch");
// When we click a button, load our new content into our popup
// and fade the window in once the request has completed. Also,
// fade our cover in, thus restricting the user from clicking the content beneath
popup_launcher.on("click", function() {
popup_window.load(child_url, function() {
popup_window.fadeIn();
content.fadeIn(cover);
});
});
// When a close button is clicked inside the popup window, fade it out.
popup_window.on("click", ".close", function() {
popup_window.fadeOut();
cover.fadeOut();
});
CSS
#cover {
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
z-index:2;
display:none;
background:RGBA(0,0,0,0.5);
}
#popup-window {
position:fixed;
left:30%;
right:30%;
top:30%;
bottom:30%;
z-index:3;
}
Very simple example, but our #cover has to be positioned beneath our #popup-window, so we use the z-index property to ensure this.
Edit - whilst the Ajax method would be nicer, bear in mind that due to HTTP access control, you'll only be able to request pages on the same domain (generally), so if you need to open external resources, you'll probably need to use an iFrame solution.

ajax: how to reopen a div after closing using ajax

I call a page with ajax in a div. when the page opens, there is a "close "button to hide the div. After clicking the close button, I need to refresh the page to reopen the div.
What should I do to open and close the div as much as I like without refreshing the page?
code:
<script>
$(document).ready(function(){
$('#close').click(function() {
$('#show_options').hide();
$(window).unload( function () { alert("Bye now!"); } );
});
});
</script>
Close <div id="show_options" style="position:absolute; width:500px; padding:10px; left: 246px; top: 41px; z-index:900;"></div>My selection: <span id="select-result" style="font-family:Arial, Helvetica, sans-serif;font- size:10pt;color:#444;">leeg</span> </div>
<a ONClick="xmlhttpPost('selected_output_team.php', 'options', 'show_options'); return false; " id="show_options"> edit</a>
I haven't tested this, but at the "close" anchor, try this:
Close
... stuff ...
Open
Once you have that, you can, instead of removing the div, simply remove (and readd) its contents:
function closeDiv()
{
document.getElementById("show_options").innerHTML = "";
}
function openDiv()
{
document.getElementById("show_options").innerHTML = "...whatever...";
}
There are other ways of course, but this is one of them. Note that I haven't tested the code.
use toggle() instead of hide() or show()
I am not an expert but if you do not want to hide or show the div tag with animation, you can simply change the visibility of the div tag using CSS. You can have the following functions to close and open the div tag:
function close() {
document.getElementById("show_options").style.display = "none";
}
function open() {
document.getElementById("show_options").style.display = "block";
}
Nice thing about CSS is that you don't have to regenerate content, therefore I think it should work faster and your code could be shorter.
I'm not really sure that I understand your question. However, if you simply wants the close-link to execute the javascript function, and nothing else, replace the "#" with "javascript:;" in the link-tag. The anchor might give you some unexpected behavior at times.

Reporting child window's events to parent window to reset timer value of user timeout code

I've got a Jquery function that I wrote which blacks out the screen after a certain amount of inactivity, creates a pop-up that allows the user to click a button to stay logged in, and logs them out (closing the application window) if they do not respond in time.
The environment is ASP.NET (VB). We don't technically use master pages, but we do have a parent page in which our header, footer and nav reside, and my Jquery code is called from that window, loaded via an IFrame.
My problem is that if one is working in a child window, the parent window doesn't recognize that the system is in use, and will automatically engage at the allocated time.
I've tried everything under the sun I can think of and nothing works properly. My event handler is working, and it does call the parent window function, but the timer is not being reset.
I have this function in the parent window:
<script language="javascript" type="text/javascript">
function window.reportChildActivity() {
SESSION_ALIVE = true;
window.setTimeout("pop_init()", SESSION_TIME);
}
</script>
And this in the child window:
<script type="text/javascript">
$(document).bind("mousedown keydown blur", function() {
window.parent.reportChildActivity(); });
</script>
No matter how much I click or use keys in the child window, my Jquery timeout code is called when SESSION_TIME runs out the first time. And then I get multiple Jquery windows in my page telling me to click to continue. It's like the events are being buffered and when they fire these windows are all being spawned multiple times. Does anyone see from this what I'm doing wrong? Thanks!
---- EDIT -----
I'm adding my pop_init function and supporting functions for reference:
// remove all added objects and restart timer
function popup_remove() {
$("#popup_window").fadeOut("fast", function() { $('#popup_window,#popup_overlay').trigger("unload").unbind().remove(); });
//if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
$("body", "html").css({ height: "auto", width: "auto" });
$("html").css("overflow", "");
//}
window.setTimeout(pop_init, SESSION_TIME);
}
// session ajax call from button click
function session_refresh() {
SESSION_ALIVE = true;
$(".buttons").hide();
$("#popup_message").html("<center><br />Thank you! You may now resume using the application.<br /></center>");
window.setTimeout(popup_remove, 1000);
$("#popup_window").fadeOut("slow", function() { $('#popup_window,#popup_overlay').trigger("unload").unbind().remove(); });
window.setTimeout(pop_init, SESSION_TIME);
}
function popup_expired() {
if (!SESSION_ALIVE)
window.close();
}
// Main popup window handler
function pop_init() {
// show modal div
$("html").css("overflow", "hidden");
$("body").append("<div id='popup_overlay'></div><div id='popup_window'></div>");
//$("#popup_overlay").click(popup_remove); // removed to make sure user clicks button to continue session.
$("#popup_overlay").addClass("popup_overlayBG");
$("#popup_overlay").fadeIn("slow");
// build warning box
$("#popup_window").append("<h1>Warning</h1>");
$("#popup_window").append("<p id='popup_message'>Your session is about to expire. Please click the button below to continue working without losing your session.</p>");
$("#popup_window").append("<div class='buttons'><center><button id='continue' class='positive' type='submit'><img src='images/green-checkmark.png' alt=''/> Continue Working</button></center></div>");
// attach action to button
$("#continue").click(session_refresh);
// display warning window
popup_position(400, 300);
$("#popup_window").css({ display: "block" }); //for safari using css instead of show
$("#continue").focus();
$("#continue").blur();
// set pop-up timeout
SESSION_ALIVE = false;
window.setTimeout(popup_expired, 30000);
}
try assigning the setTimeout to a global variable and clearing it each time eg:
var timer=false;
window.reportChildActivity = function() {
if(timer!==false) {
clearTimeout(timer);
}
SESSION_ALIVE = true;
timer=window.setTimeout(pop_init, SESSION_TIME);
}
example: http://jsfiddle.net/pB2hX/1/

Categories