Attaching callback to popup window in IE 9 - javascript

I'm creating a popup window and attaching a callback function to it. There is a button in the popup's page which calls this callback when clicked. This works in Firefox 4 and Chrome 10, but not IE 9. The "myPopupCallback" property that I add to the window is found and executed by Firefox and Chrome. In IE, it is undefined.
Is there something about IE that causes problems with attaching data or functions to a window?
Main window code
var popup = window.open(url, '', 'status=0,menubar=0,toolbar=0,resizable=1,scrollbars=1');
$(popup.document).ready(function()
{
popup.myPopupCallback = function(rows)
{
// ...do stuff with rows...
};
});
Popup window code
$('#btn-ok').click(
function()
{
var rows = $('#rows');
// IE 9 throws an error on the next line because window.myPopupCallback is undefined
window.myPopupCallback(rows);
});

window.open() is a non-blocking operation which means that before the new window has finished opening JavaScript will move on to next line of code. Because of this, setting a property may not "stick" if it's done too soon. I just ran into this problem myself.
Thanks to a lot of help from Erik I found the following seems to work pretty well.
var popup = window.open(
url, '', 'status=0,menubar=0,toolbar=0,resizable=1,scrollbars=1'
);
$(popup.document).ready(function(){
var setPopupPropertiesInterval = setInterval(
function setPopupProperties() {
popup.myPopupCallback = function(rows)
{
// ...do stuff with rows...
};
if (popup.closed || popup.myPopupCallback) {
clearInterval(setPopupPropertiesInterval);
}
}, 1
);
});
This will keep trying to add the function to the popup window until it is added or the popup window is closed.
In my extremely brief testing this worked across browsers but I'm not sure about the performance implications of such a fast interval and had no issues with performance. Note that most (all?) browsers will not actually run the code in 1 ms intervals, but something a bit higher, usually 10 ms. Chrome is an exception to this in that it tries to get close to 1 or 2ms.
On one Windows XP machine running IE 7 I ran into an issue where the browser would freeze upon launching the pop-up. The window would pop-up but nothing would load and the browser would become slow to respond. However, I have tested this on several other machines running Windows XP and IE 7 and was not able to reproduce the issue.

Related

SWFObject event undefined in Chrome works in IE

I want to get the currentFrame of my Flash movie when it is loaded. I followed the the tutorial found here http://learnswfobject.com/advanced-topics/executing-javascript-when-the-swf-has-finished-loading/index.html and SWFOBJECT CurrentFrame Javascript. I am using SWFObject 2.3 beta. This works perfectly fine on Internet Explorer however it does not work on Google Chrome.
In Chrome I get the error
Uncaught TypeError: e.ref.currentFrame is not a function
Checking e it returns [object Object]
Checking e.ref returns [object HTMLObjectElement]
Checking e.ref.totalFrames returns undefined
var flashvars = {};
var params = {};
var attributes = {};
function mycall(e){
setInterval(function(){console.log("Frame: " + e.ref.currentFrame)},1000);
}
swfobject.embedSWF("notmyswf.swf", "course", "100%", "100%", "6.0.0", false, flashvars, params, attributes, mycall);
Why is this not working on Chrome but works well with IE? Is the event e not detected? Is there a work-around on how to make this work on Chrome?
The purpose of this is for me to create a check if the user is really using the course he has opened and not just leaving it idle. I have already added a code that will check idle but it is not enough. Most learners, have figured out a way to just open a course, leave it there to accumulate hours of training. Some even have a program running in their computers that will just move the mouse 1-pixel every few seconds so that the computer does not go to idle. If I can check the current frame of the Flash movie, I can create a function that will calculate the current page the user is viewing every 15 minutes. If he is stuck in the same page I can then show a prompt that the user must click in order to continue viewing the course or it will automatically close.
I suggest dropping the SWF-based currentFrame approach in favor of monitoring your calls to the database using JavaScript. (Based on your comments, it sounds like the DB calls are being sent by JS, so this shouldn't be a problem.)
If the course bookmark is auto-saved every 3 minutes (as described in your comments), you can cache the value in your page's JS and do a compare every time the save is performed. If the value hasn't changed in x number of minutes, you can display your timeout warning.
If you're using a SCORM wrapper (or similar), this is really simple, just modify the wrapper to include your timer code. Something like:
//Old code (pseudocode, not tested)
function setBoomark (val){
API.SetValue("cmi.core.lesson_location", val);
}
//New code (pseudocode, not tested)
var current_location = "";
var activityTimer;
function disableCourse(){
//do stuff to disable course because it timed out
}
function setBoomark (val){
API.SetValue("cmi.core.lesson_location", val);
if(val === current_location){
//do nothing, timer keeps ticking
} else {
//reset timer using new bookmark value
if(activityTimer){ clearTimeout(activityTimer); }
activityTimer = setTimeout(disableCourse, 15000);
//Update current_location value
current_location = val;
}
}
This is a rough sketch but hopefully you get the idea.
I feel stupid!
It did not work in Chrome and Firefox because I used the wrong casing for the functions but in IE11 it works no matter the case.
So the correct functions are:
e.ref.CurrentFrame() //I used currentFrame() which still works in IE11
e.ref.TotalFrames() //I used totalFrames() which still works in IE11
e.ref.PercentLoaded() //I used this correctly and was able to get the value

In a Firefox restartless add-on, how do I run code when a new window opens (listen for window open)?

I am starting to build a restartless Firefox add-on and I am having trouble setting up the bootstrap.js. Everyone seems to agree that the core of a bootstrap.js is pretty much boilerplate code, along these lines:
const Cc = Components.classes;
const Ci = Components.interfaces;
function startup() {
let wm = Cc["#mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
let windows = wm.getEnumerator("navigator:browser");
while (windows.hasMoreElements()) {
let domWindow = windows.getNext().QueryInterface(Ci.nsIDOMWindow);
// then can control what happens with domWindow.document
}
}
function shutdown() {}
function install() {}
function uninstall() {}
This code works and I can control things in the existing windows. For example, domWindow.alert("text") successfully creates a standard alert saying "text" on every window that is currently open.
However, I can't find any code that will allow me to do things in new windows; i.e. those created after the script runs. What is the correct way to handle the creation of new windows and gain control over them, to the point where I could get another "text" alert from one when it is created?
Edit: Using the nsWindowMediator class and the code sample from MDN, I now have this:
var windowListener = {
onOpenWindow: function (aWindow) {
try {
let domWindow = aWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
domWindow.addEventListener("load", function () {
domWindow.removeEventListener("load", arguments.callee, false);
//window has now loaded now do stuff to it
domWindow.alert("text");
}, false);
} catch (err) {
Services.prompt.alert(null, "Error", err);
}
},
onCloseWindow: function (aWindow) {},
onWindowTitleChange: function (aWindow, aTitle) {}
};
function startup(aData, aReason) {
// Load into any existing windows
try {
let wm = Cc["#mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
let windows = wm.getEnumerator("navigator:browser");
while (windows.hasMoreElements()) {
let domWindow = windows.getNext().QueryInterface(Ci.nsIDOMWindow);
loadIntoWindow(domWindow);
}
} catch (err) {
Services.prompt.alert(null, "Error", err);
}
Services.wm.addListener(windowListener);
}
However, there is still no output from the onOpenWindow call - the "text" alert does not appear, nor does the error alert in the catch block. I can confirm that onOpenWindow is actually being entered; if I put a Services.prompt.alert() at the beginning of onOpenWindow, I get the alert when I create a new window. Unfortunately, I get an infinite loop of alerts and I have no idea why.
However, I can't find any code that will allow me to do things in new windows; i.e. those created after the script runs. What is the correct way to handle the creation of new windows and gain control over them, to the point where I could get another "text" alert from one when it is created?
The correct way to act on each window when it opens is to use addListener() from nsIWindowMediator. The example code below does this. The nsIWindowMediator is included in Services.jsm and is accessed through Services.wm.addListener(WindowListener). In order to use a window listener, you have to pass it an nsIWindowMediatorListener (ref2) object. An nsIWindowMediatorListener contains three keys: onOpenWindow, onCloseWindow, and onWindowTitleChange. Each should be defined as a function which will be called when the appropriate event occurs.
The MDN document How to convert an overlay extension to restartless in "Step 9: bootstrap.js" contains an example of a basic bootstrap.js which will run the code in the function loadIntoWindow(window) for each currently open browser window and any browser window which opens in the future. I have used code modified from this in a couple of different add-ons. The example is substantially similar to the code you are already using. The example is (slightly modified):
const Ci = Components.interfaces;
Components.utils.import("resource://gre/modules/Services.jsm");
function startup(data,reason) {
// Load this add-ons module(s):
Components.utils.import("chrome://myAddon/content/myModule.jsm");
// Do whatever initial startup stuff is needed for this add-on.
// Code is in module just loaded.
myModule.startup();
// Make changes to the Firefox UI to hook in this add-on
forEachOpenWindow(loadIntoWindow);
// Listen for any windows that open in the future
Services.wm.addListener(WindowListener);
}
function shutdown(data,reason) {
if (reason == APP_SHUTDOWN)
return;
// Unload the UI from each window
forEachOpenWindow(unloadFromWindow);
// Stop listening for new windows to open.
Services.wm.removeListener(WindowListener);
// Do whatever shutdown stuff you need to do on add-on disable
myModule.shutdown();
// Unload the module(s) loaded specific to this extension.
// Use the same URL for your module(s) as when loaded:
Components.utils.unload("chrome://myAddon/content/myModule.jsm");
// HACK WARNING: The Addon Manager does not properly clear all add-on related caches
// on update. In order to fully update images and locales, their
// caches need clearing here.
Services.obs.notifyObservers(null, "chrome-flush-caches", null);
}
function install(data,reason) { }
function uninstall(data,reason) { }
function loadIntoWindow(window) {
/* call/move your UI construction function here */
}
function unloadFromWindow(window) {
/* call/move your UI tear down function here */
}
function forEachOpenWindow(todo) {
// Apply a function to all open browser windows
var windows = Services.wm.getEnumerator("navigator:browser");
while (windows.hasMoreElements())
todo(windows.getNext().QueryInterface(Ci.nsIDOMWindow));
}
var WindowListener = {
onOpenWindow: function(xulWindow) {
var window = xulWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
function onWindowLoad() {
window.removeEventListener("load",onWindowLoad);
// Only add UI changes if this is a browser window
if (window.document.documentElement.getAttribute("windowtype")
== "navigator:browser")
loadIntoWindow(window);
}
window.addEventListener("load",onWindowLoad);
},
onCloseWindow: function(xulWindow) { },
onWindowTitleChange: function(xulWindow, newTitle) { }
};
While there is quite a bit more that your might want to do in your bootstrap.js code, the above is organized reasonably well and keeps all of the code to load into the Firefox UI within loadIntoWindow(window) and unloading the UI within unloadFromWindow(window). However, it should be noted that some UI elements you should only be adding/removing once (e.g. australis widgets, like buttons) and other elements (e.g. direct changes to the Firefox DOM) have to be added once in each window.
Unfortunately, I get an infinite loop of alerts and I have no idea why.
One of the significant differences between this example and what you are currently using is the test for the type of window that has opened. This is done so that we are only acting on newly opened windows which are browser windows instead of all newly opened windows:
if (window.document.documentElement.getAttribute("windowtype") == "navigator:browser")
loadIntoWindow(window);
The problem you describe of getting an infinite loop of alert() popups is caused by not checking to make sure that you are only acting on browser windows. The alert() popup is a window. Thus, you are calling alert() for every alert() window you open which, of course, just opens another alert() window on which you call alert(). This is your infinite loop.
Additional references:
1. Working with windows in chrome code
However, I can't find any code that will allow me to do things in new windows
When working with XPCOM objects you generally want to study their interfaces, which are often found on MDN. In this case your starting point would be nsIWindowMediator, since that's the service you're using in line 5.
As you can see it has an addListener function, which takes a parameter implementing nsIWindowMediatorListener. There's a code-example right there on the page.
But let's assume for the moment there isn't a code example. You could search for the interface on MDN, but it isn't listed. The next step would be searching MXR for the .idl. idl = interface description language
Once you got the interface contract you can more or less just implement it in javascript, at least for listeners. Implementing your own xpcom services would be a little more complicated.
Searching the addon sdk can often provide some hints too. In this case they don't seem to be using .addListener, but the file hints at another interesting service, which in turn you can find on MDN: nsIWindowWatcher.
Basically, if you're writing restartless addons you're rummaging through the entrails of firefox and will have to do some detective work to find the exact components you need. If you want something more convenient I would recommend the addon sdk, which provides a more organized but also more restricted set of commonly used APIs

Issues with GridView on IE but not on Firefox

IE takes forever to load my GridView where as Firefox is almost instant (big surprise I know; but you know users and how they love IE).
We have a GridView which when the user scrolls to the bottom loads more entries into the list (basically lazy loading, instead of loading the whole list, it loads 20 entries and when you scroll to the bottom it loads the next 20). However like I said there is a huge difference in how this performs on IE vs FF. When debugging on IE I consistently get Javascript timeout errors.
during this code block:
function Sys$WebForms$PageRequestManager$_endPostBack(error, executor, data) {
if (this._request === executor.get_webRequest()) {
this._processingRequest = false;
this._additionalInput = null;
this._request = null;
}
var handler = this._get_eventHandlerList().getHandler("endRequest");
var errorHandled = false;
if (handler) {
var eventArgs = new Sys.WebForms.EndRequestEventArgs(error, data ? data.dataItems : {}, executor);
handler(this, eventArgs);
errorHandled = eventArgs.get_errorHandled();
}
if (error && !errorHandled) {
throw error;
}
}
This error AFAIK is the reason we implemented lazy loading (to get rid of the timeouts). However it seems to not be helping, merely duplicating the issue every time is runs. NOTE: prior to our last release it would load all the data as opposed to Lazy Loading.
Also when debugging it seems to cycle on this piece of code when it is "loading" on IE:
Protected Overrides ReadOnly Property ControlSkins() As System.Collections.IDictionary
Get
Return Me.__controlSkins
End Get
End Property
I believe due to fact that FF displays the data without the timeout that whatever is causing this is specific to IE and maybe common to other implementation of a GridView population.
I should note however that Im not positive that FF communicates with VS like IE does. Meaning that the warnings I get (the screenshot above) might happen on FF and VS doesnt show them to me but like I said FF has no problems with our page.
Followup [similar error q/a]:
After further testing the ControlSkins() method that is getting called repeatedly (posted above) here is its value. It alternates between that HybridDictionary and Nothing
I have to continue testing but I think/hope (fingers are crossed) that adding AsyncPostBackTimeout="300" on my ScriptManager (for that widget) has stopped the timeout error. Of course this doesn't help with the large load times on IE.

Bring spell check window to foreground with JavaScript/JScript in Windows 7

I have some JScript code (converted from some old VBScript) that starts like this:
var Word = new ActiveXObject("Word.Basic");
Word.FileNew(); // opens new Word document
Word.Insert(IncorrectText);
Word.ToolsSpelling(); // opens spell check behind IE
The idea is to utilize the MS Word spell check for browser use, and it works well in XP, but the spell check box opens in the background in Windows 7 / IE 8 (this question tells me that the problem started in Vista and is probably an OS issue, not a browser or Office issue).
So my question is, how can I bring this window to the foreground? One important note is that the last line, Word.ToolsSpelling();, locks up my script, so anything I do will need to be before that.
I've tried
var wshShell = new ActiveXObject("WScript.Shell");
wshShell.AppActivate("Document1 - Microsoft Word"); // or some other text
before the ToolsSpelling call, but this does not do anything (maybe because the Word document is not actually revealed at this point?). Of course, this will only work if no "Document1" is already opened, so this is a questionable thought to begin with.
Per this answer, I tried using window.blur(); in order to blur IE, but this will only work if the IE window is the only one opened. Maybe there's some way I can loop through all opened windows and apply this?
SetForegroundWindow looked promising, but I don't know how to use it in JSript.
Any ideas?
Note: Browser permissions will be completely open for this site.
Update: Turns out if you use Word.Application, the spell check comes up in front as it should. Only the Word.Basic method has this problem (I don't expect to know why this side of eternity):
var wordApp = new ActiveXObject("Word.Application");
wordApp.Documents.Add();
wordDoc = wordApp.ActiveDocument;
... // safety checks before insertion
wordSelection.TypeText(IncorrectText);
wordDoc.CheckSpelling();
wordApp.Visible = false; // CheckSpelling makes the document visible
You might be able to jigger the window state. When the window is maximized after having been minimized, Windows will stack that in front (zIndex to top).
Something like:
var WIN_MAX = 2;
var WIN_MIN = 1;
var Word = new ActiveXObject("Word.Application");
Word.Visible = true;
// minimize the app
Word.WindowState = WIN_MIN ;
// in 500ms, maximize
setTimeout(function () {
Word.WindowState = WIN_MAX;
}, 500);
The setTimeout call seeks to work around a timing issue; Windows will sometimes "get confused" when a programmatic minimize/maximize happens in immediate succession. You might have to extend that delay a little, test it repeatedly and see what kind of results you get.

window.open() is not working in IE6 and IE7

I have a dotnet application in which I have to close the current window and then open the new window again in runtime. I have used Javascript for it. The code is as follows:
function OpenNewWindow() {
if (ConfirmStartTest()) {
closeWindow();
window.open("OnlineTestFrame.aspx", "_Parent", "model=yes,dailog=no,top=0,height=screen.height,width=screen.width,status=no,toolbar=no,menubar=no,location=no,zoominherit =0,resizable =no,scrollbars=yes,dependent=no,directories=no,taskbar=no,fullscreen=yes");
self.focus();
}
}
//taking the confirmation for starting test
function ConfirmStartTest() {
var result = confirm("Do you want to start the test now?");
return result;
}
//function to close the current window
function closeWindow() {
//var browserName = navigator.appName;
//var browserVer = parseInt(navigator.appVersion);
var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
if (ie7)
{
//This method is required to close a window without any prompt for IE7
window.open('','_parent','');
window.close();
}
else
{
//This method is required to close a window without any prompt for IE6
this.focus();
self.opener = this;
self.close();
}
}
Now, when I am running this application in IE7 and IE6, it is not running. But, in IE8 it is running fine.
This code was working fine for all IE6 n IE7 previously. All of a sudden it is giving error.Its not able to open the new window and stopping abruptly in b/w.
If anyonw has any idea regarding this, please let me know.
This is due to the assignment of self.opener.
12/04 Microsoft started pushing out Security Bulletin MS11-018 via Windows Update which closed of several vulnerabilities related to memory - one of these affected the opener property which no longer can be assigned to.
Nothing like closing a window and expecting anything after it to want to run.
Flow of the code
Function called
Close Window
Open window <-- How can I run if parent is closed?
Focus window
[rant]
What you are trying to do here by forcing a user to use your own pop up window so it has no chrome is very bad user experience. You are deleting a users history. Leave my browser alone! There is a reason why you have to do hacky stuff to close a window, the browsers do not allow you to do it.
[/rant]

Categories