Pop up window self close function; close the site as well - ajax

I have an Ajax call back function which call to a PHP function check the file modified time.
I uses timer to execute it every 50 seconds.
<script type="text/javascript">
setInterval("_checkPopUpUpdate()", 50000); //50 seconds
</script>
function _checkPopUpUpdate()
{
var callback=new Object();
callback.success=this.onExternalSuccess;
callback.failure=this.onExternalFailure;
YAHOO.util.Connect.asyncRequest('GET','/ci/ajaxCustom/ajaxCheckPopupUpdate',callback);
};
The PHP function checks whether the file modified time has different between the first load session time
$announcement_Popup_Path = HTMLROOT . $this->data['attrs']['file_path'];
// Call model function
if($this->data['attrs']['file_path'] !== '' && file_exists($announcement_Popup_Path))
{
//When the announcement content load, it always stores the modified time into session
$this->CI->load->model('custom/checkupdate_model');
$firstloadTime = filemtime($announcement_Popup_Path);
$this->CI->checkupdate_model->store_AnnouncementPopupSession($firstloadTime);
//$this->data['Popup'] = file_get_contents($announcement_Popup_Path);
}
function store_AnnouncementPopupSession ($popupTime)
{
$sessionPopupTime =array("annoucementPopUp"=> $popupTime);
$this->session->setSessionData($sessionPopupTime);
}
function announcement_pop()
{
$file_path='/euf/assets/announcements/pop_up_announcement.html';
$announcement_Popup_Path = HTMLROOT . $file_path;
if(file_exists($announcement_Popup_Path)) {
$currentAnnouncementPopUpTime = filemtime($announcement_Popup_Path);
$oldannouncementPopupTime = $this->session->getSessionData("annoucementPopUp");
if($currentAnnouncementPopUpTime !=$oldannouncementPopupTime) {
//comparing the content and update the time, when they are different, send back update content
$this->store_AnnouncementPopupSession($currentAnnouncementPopUpTime);
//echo $currentAnnouncementPopUpTime;
echo $file_path;
}
else {
echo "no update";
}
}
}
When the file modifed time has changed, it will return to ajax call back and grab the HTML content in my web server to Pop up an annoucement pop up window.
function onExternalSuccess (o){
if(o.responseText!==undefined)
{
var str=o.responseText;
if(str !== 'no update') // Then pop up.
{
L=screen.width-200;
T=screen.height;
popup=window.open(str," ",'alwaysRaised=yes,status=no,toolbar=no,location=no,menubar=no,directories=no,resizable=no,scrollbars=no,height=150,width=364,left="+L+",top="+T');
//popup=window.open(str,"",'alwaysRaised=yes,status=no,toolbar=no,location=no,menubar=no,directories=no,resizable=no,scrollbars=no,height=100,width=330');
for (i=0;i<200;i++)
{
T=T-1;
popup.moveTo(L,T);
}
}
}
};
It works fine for Firefox and Chrome, however IE7 is a bit bugy, sometime the pop up does not come out.
<html>
<head>
<title>Internal alert</title>
<link rel="stylesheet" type="text/css" href="/euf/assets/css/pop_up_ann.css" media="screen, projection" />
<script type="text/javascript">
var howLong = 50000; //5 minutes, 1 seconds = 1000 milliseconds.
t = null;
function closeMe(){
t = setTimeout("self.close()",howLong);
}
</script>
</head>
<body onLoad="closeMe();self.focus();">
<div id="cs_popup">
<div class="popup_rounded-corner-top">
<div id="popup_ann">
<div id="popup_ann_title">IE7 pop-up EMEA test close </div>
<div id="popup_ann_from"> PLC team - 05/01/2011 at 12:10</div>
<div id="popup_ann_content">
Something has changed in the<em>"Alerts"</em> section of S4S since your last visit.
Make sure you go there as soon as you can to be informed about the current situation.
</div>
</div>
</div>
<div class="popup_rounded-corner-bottom"></div>
</div>
</body>
</html>
The main problem i have here it is self-close function. It close my pop up window and the website as well. Any hints? Also, i am not sure whether my whole pop up annoucement logical structure is correct, is there anyway? thanks

Opening a popup window for an announcement like this could be problematic for people running popup blockers, which typically only allow popups to appear in response to a user-initiated event like clicking on something. A better approach would be to use an inline popup which would also give you the opportunity to display the popup modally (i.e. mask the rest of the page with a semi-transparent div) if you require them to acknowledge your message.
The use of self.close() should not close the original window/tab opened by the user, it should only close things that have been 'open'ed so I'm not sure what's going on there, I suspect you haven't told us everything :) An alternate approach might be to modify your popup function to close the window rather than have the window close itself.
// open popup ... then set timeout to close it
var popupDelay = 50000;
setTimeout(function() {
popup.close();
}, popupDelay);
This may work a little better, not sure. But in the long run, I highly recommend avoiding popups and using something inline instead.

Related

Modal Dialog fails to close on submission once ui.alert is Commented out

Why should the Commenting out of a ui.alert cause the submission of a Modal Dialog to fail to close on submission? The functions still actually do what they are supposed to do, but the Dialog won't go away; you have to click the close button. I've been using Alert Boxes to troubleshoot my work, and now as I Comment them out, I find that there is one that I can't, without producing this problem.
The line in question is the only one commented out here:
function getStartFromDialog (form) {
scriptProperties.getProperties();
var option1 = scriptProperties.getProperty('savedOption1');
var option2 = scriptProperties.getProperty('savedOption2');
var eRow = scriptProperties.getProperty('savedRow');
var tabName = scriptProperties.getProperty('savedTab');
var start = form.chosenStart;
// ui.alert ('Chosen option is '+ start);
if (start == 'option1'){var adjustedStart = option1}
else {var adjustedStart = option2}
reactToUserEntryOfStart (adjustedStart,eRow);
}
Here is the index.htm file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script>
function submitForm() {
google.script.run.getStartFromDialog(document.getElementById("startChoiceForm"));
document.getElementById("form").style.display = "none";
}
</script>
</head>
<body>
<div>
<div id="form">
<? var offeredStart1 = offeredStarts[0]; var offeredStart2 = offeredStarts[1] ?>
<form id="startChoiceForm">
<select name="chosenStart" id ="chosenStart">
<option value="option1"><?= offeredStart1 ?></option>
<option value="option2"><?= offeredStart2 ?></option>
</select>
<div>
<input type="submit" value="Submit" class="action" onclick="submitForm()" >
<input type="button" value="Close" onclick="google.script.host.close()" >
</div>
</form>
</div>
</body>
</html>
This video demonstrates:
Functions working;
My Commenting out that line ui.alert ('Chosen option is '+ start);
Same procedure; now Dialog Box hangs.
The scripts allow the user to enter times in testUserEntTime!A3:A without typing a colon or specifying AM/PM, ie 325 for either 3:25am or 3:25pm. It automatically turns these entries into date-time values so that they are always sequential top-to-bottom, permitting no date-time to be earlier than the one before.
The dialog box is triggered by the entering of a time which has the same hour as the time above it, but earlier minutes.
In the video, the previous time is 4:55 am 9/5/2001 (formatted so only the time shows) and I am entering 450. This causes the script to ask whether I intend to indicate 4:50pm, or 4:50am on the next day, 9/6.
Thank you for your help; I'm bewildered.
YouTube video demonstrating bug
When I saw your sample Spreadsheet and your current script, in your situation, how about the following modification?
From:
google.script.run.getStartFromDialog(document.getElementById("startChoiceForm"));
To:
google.script.run.withSuccessHandler(google.script.host.close).getStartFromDialog(document.getElementById("startChoiceForm"));
When ui.alert ('Chosen option is '+ start); is used in the function getStartFromDialog, the dialog is overwritten by ui.alert. By this, when the ok button is clicked, the dialog is closed. When you want to close the dialog by clicking submit button, google.script.host.close is run using withSuccessHandler.
Reference:
withSuccessHandler(function)

Cannot call getUI from this context when using google.script.run

I'm making a program that will automatically open the launch meeting page to take me to my next ZOOM class on time, and our schools have 'a days' and 'b days', each with a different schedule, so I have an HTML page that has two buttons, one that will trigger the schedule for an A day and another that triggers the schedule for a B day. I'm testing the functions that will open the new tab and run that function from the HTML, but when I run it from the HTML, I get an error message in my executions that says cannot call DocumentApp.getUI from this context. My code is here, if you put it into GAS you can see for yourself.
Part of my code came from this answer
My code.gs file
function doGet() {
return HtmlService.createHtmlOutputFromFile('index.html');
}
function openUrl( url ){
var html = HtmlService.createHtmlOutput('<html><script>'
+'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
+'if(document.createEvent){'
+' var event=document.createEvent("MouseEvents");'
+' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+' event.initEvent("click",true,true); a.dispatchEvent(event);'
+'}else{ a.click() }'
+'close();'
+'</script>'
+'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+'</html>')
.setWidth( 90 ).setHeight( 1 );
DocumentApp.getUi().showModalDialog( html, "Opening ..." );
}
function LaZoom(){
openUrl('https://op97-org.zoom.us/j/9622570589');
}
My HTML file
<!DOCTYPE html>
<html>
<button onclick = 'aDay()'>A day</button>
<button onclick = 'bDay()'>B day</button>
</html>
<script>
function aDay(){
google.script.run.LaZoom();
alert('ran')
}
</script>
You can easily do this client side using window.open instead of going back and forth between server and client.
function aDay(){window.open('A_URL')}

firefox web extension tutorial: script repeat itself

I've followed the following guide to train myself at firefox addon:
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Your_second_WebExtension
Then I started tweaking the code to add my own functions, keeping the same architecture/logic.
But then I noticed that my functions, when launched by clicking in the menu, execute sereval times, actually the number of times I've clicked in the addon menu since I loaded the page.
example: I created a menu option called Repeat Test that links to a function called "Repeat Test" that is just console.log('1');
- first click, I get 1
- second click, I get 1 / 1
- third click, I get 1 / 1 / 1
where can that come from ?
my code:
beast.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="choose_beast.css"/>
</head>
<body>
<div class="beast">Remove Model Map</div>
<div class="beast">Color Formulas</div>
<div class="beast">Image Overlay</div>
<div class="beast">Repeat Test</div>
<script src="choose_beast.js"></script>
</body>
</html>
choose_beast.js:
function optionSelection(myvar) {
switch (myvar) {
case "Remove Model Map":
return "modelMap";
case "Color Formulas":
return "colorFormulas";
case "Image Overlay":
return "imageOverlay";
case "Repeat Test":
return "repeatTest";
}
}
document.addEventListener("click", function(e) {
if (!e.target.classList.contains("beast")) {
return;
}
var clickedOption = e.target.textContent;
var optionActivated = optionSelection(clickedOption);
chrome.tabs.executeScript(null, {
file: "/content_scripts/beastify.js"
});
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {option: optionActivated});
});
});
and finally, beastify.js:
function myaddon(request, sender, sendResponse) {
switch (request.option){
case "modelMap": removeModelMap();
case "colorFormulas" : colorFormulas();
case "imageOverlay" : overlay();
case "repeatTest" : repeatTest();
}
}
function repeatTest()
{
console.log('1');
}
chrome.runtime.onMessage.addListener(myaddon);
I've found the issue here. this code
chrome.tabs.executeScript(null, {
file: "/content_scripts/beastify.js"
});
is contained into the click event manager, so every time you click, the script is executed, which adds to the fact that later on a message is sent to the script every time a click is made.
I don't know if this is a mistake or not (it's actually like this on the mozilla website):
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Your_second_WebExtension
but it was quite annoying for me. I'll notify them.

Problems with mouse events on newly created CKEditor instance

I'm trying to create a create a new CKEditor ver4 instance in response to the user clicking on an element. Due to the nature of the application, I can not use the "autoInline" feature as outlined in the CKEditor Sample. While the sample below does in fact create an editor instance, that instance has a significant problem. Inline instances are supposed to disappear when the user clicks away from them. In this example however, the user must first click away, click back into the instance, and then click away again. How can I prevent this?
<!doctype html>
<html>
<head>
<script src="jspath/ckeditor.js"></script>
<script>
var editor = null;
CKEDITOR.disableAutoInline = true;
function init() {
var e2 = document.getElementById("element2");
e2.addEventListener("click", function () {
if(!editor) {
editor = CKEDITOR.inline(e2);
editor.on('instanceReady', function () {
console.log("instanceReady")
console.log(editor.focusManager.hasFocus);
});
editor.on('focus', function() {
console.log("focus");
})
editor.on('blur', function() {
console.log("blur");
editor.destroy();
editor = null;
})
}
})
}
</script>
</head>
<body onload="init()">
<div tabindex="0" id="element2" style="background-color: yellow;" contentEditable = true>Element 2</div>
</body>
</html>
Despite the fact that editor.focusManager.hasFocus was true, the editor's element did not in fact have focus. Perhaps this is a bug? Anyway, adding editor.focus(); to the instanceReady function resolved the issue.

Partial page refresh for evary X seconds with Jquery and Ajax?

1) I have to change images dynamically according to values for every x seconds.
I'm using the following function:
setInterval(function() {
$("#content").load(location.href+" #content>*","");
}, 5000);
It works fine for updating the value, but the images not getting updated into its position.
2) From the 1st question i want to know whether the jquery and css files included in the head tag will load every x seconds or not. if not how to load?
Please give me the suggestion.
If you are returning a whole HTML page and returning it into the body of another page, that is a bad idea.
Think about it, your html structure would be something like
<doc type>
<html>
<head>
</head>
<body>
<div>
<doc type>
<html>
<head>
</head>
<body>
<div>
</div>
</body>
</html>
</div>
</body>
</html>
Ideally you should be retuning just the content that is to be displayed, not everything.
If you are just updating images, there usually is no need to make an XHR call. You can just set the image src and force the browser to update that content that way.
Does this need to be done with Ajax at all? How many images are you going to cycle through? If it is only a few, just keep all of the src's on the page and switch the image src attribute periodically. This requires no page reload. You may also want to preload all the images so there is no flicker when changing to the other image. For example:
$(function () {
var images = ['1.png', '2.png', '3.png'];
$.each(images, function (index, src) {
$("<img />").attr('src', src); //preload
});
var keep = 1;
setInterval(function () {
$("#main_img").attr('src', images[keep]);
keep++;
if (keep >= images.length) { keep = 0; }
}, 5000);
});
Now if you don't want to hard code the image urls in the JS, you can load them initially with a single Ajax request.
I would only recommend using Ajax to do all the work if you are talking about an unpredictable set of images or some massive number of images.

Resources