I have a Mootools asset created like so:
// Create a new asset
var asset = new Asset.image(path, {
title: this.language.download,
events: {click: this.download.bind(this, link)},
});
I have a method of a MooTools object defined as such:
download: function(e) {
// The path to download
console.log('download: ' + e);
},
In Firefox the console.log print shows up. In IE8, however, I have no luck. Am I missing something?
Any tips or advice would be greatly appreciated. TIA!
I have tried to implement this using the two methods described. Neither seem to work in IE8 or IE8 with compatibility mode.
var path = this.options.assetBasePath + 'disk.png';
var _this = this;
var icon = new Asset.image(path, {
/*onload: function() {
this.set({
title: _this.language.download,
events: {click: function() {
alert('test');
}
}
}).inject(el, 'top');
}*/
});
icon.set({title: _this.language.download,
events: {click: function() {
alert('test');
}
}
});
icon.inject(el, 'top');
icon.addClass('browser-icon');
icons.push(icon);
Both of these methods display an alert() just fine in FF but fail in IE.
In view of further communication via email... and the fact that the issue is caused by the use of filemanager mootools plugin by cpojer (of the mootools core team), I am updating my reply to the advice given via email as well.
source code in question: http://github.com/cpojer/mootools-filemanager/raw/master/Source/FileManager.js - line 408 is the problem
The reason why the original code may fail (in IE8) but i'd consider it unsafe as is anyway - is that events in mootools are UID driven per element. I.E. - if you inject an element or pass it through a selector and possibly create it via new Element() class (tbc), it assigns it a UID against which element storage is enabled. It is possible that the chaining used in the original form results in the addEvent running before the element exists which would cause it to fail. The issue here is WHY would it fail to attach the events when all tests I have conducted seem to work. Basically, the Asset.image code goes:
var image = new Image();
var element = document.id(image) || new Element('img');
element.store("foo", "bar");
alert(element.retrieve("foo") || "failed");
this DOES assign a UID and makes it available for events even before it's a member of the DOM. tescase: http://fragged.org/dev/ie8-new-image-bug.php - does that output 'bar' for you? if so, there is no reason to suspect foul play on the order of assignment of events vs DOM insertion due to storage anyway, it could be a total manipulation issue / onclick problem.
Either way, you can try replacing the code in the class with this, аlthough I have not tested it:
var _this = this;
icons.push(new Asset.image(this.options.assetBasePath + 'disk.png', {
title: this.language.download
"class": 'browser-icon',
onload: function() {
// once the src has been set and image loaded
// inject into DOM (hence open to manilulations) and then add the event
this.inject(el, 'top').addEvent('click', function(e) {
_this.tips.hide();
e.stop();
window.open(_this.options.baseURL + _this.normalize(_this.Directory + '/' + file.name));
});
}
}));
also to consider: IE has - in the past - been known to have issues with cached images being loaded up failing to trigger events if the assignment of the event is wrong way around:
// wrong:
var image = new Image();
image.src = 'image.jpg';
image.onload = function() { // evil, won't work if image already cached, it won't trigger
...
};
// right:
var image = new Image();
image.onload = function() { // always fires the event.
...
};
image.src = 'image.jpg';
this is just as a clue, mootools ensures the correct order of insertion vs event assignment anyway - but that does not mean that IE8 has no other similar issues to do with events.
Related
I'm using JavaScript with the jQuery library to manipulate image thumbnails contained in a unordered list. When the image is loaded it does one thing, when an error occurs it does something else. I'm using jQuery load() and error() methods as events. After these events I check the image DOM element for the .complete to make sure the image wasn't already loaded before jQuery could register the events.
It works correctly except when an error occurs before jQuery can register the events. The only solution I can think of is to use the img onerror attribute to store a "flag" somewhere globally (or on the node it's self) that says it failed so jQuery can check that "store/node" when checking .complete.
Anyone have a better solution?
Edit: Bolded main points and added extra detail below:
I'm checking if an image is complete (aka loaded) AFTER I add a load and error event on the image. That way, if the image was loaded before the events were registered, I will still know. If the image isn't loaded after the events then the events will take care of it when it does. The problem with this is, I can easily check if an image is loaded already, but I can't tell if an error occurred instead.
Check the complete and naturalWidth properties, in that order.
https://stereochro.me/ideas/detecting-broken-images-js
function IsImageOk(img) {
// During the onload event, IE correctly identifies any images that
// weren’t downloaded as not complete. Others should too. Gecko-based
// browsers act like NS4 in that they report this incorrectly.
if (!img.complete) {
return false;
}
// However, they do have two very useful properties: naturalWidth and
// naturalHeight. These give the true size of the image. If it failed
// to load, either of these should be zero.
if (img.naturalWidth === 0) {
return false;
}
// No other way of checking: assume it’s ok.
return true;
}
Another option is to trigger the onload and/or onerror events by creating an in memory image element and setting its src attribute to the original src attribute of the original image. Here's an example of what I mean:
$("<img/>")
.on('load', function() { console.log("image loaded correctly"); })
.on('error', function() { console.log("error loading image"); })
.attr("src", $(originalImage).attr("src"))
;
Based on my understanding of the W3C HTML Specification for the img element, you should be able to do this using a combination of the complete and naturalHeight attributes, like so:
function imgLoaded(imgElement) {
return imgElement.complete && imgElement.naturalHeight !== 0;
}
From the spec for the complete attribute:
The IDL attribute complete must return true if any of the following
conditions is true:
The src attribute is omitted.
The final task that is queued by the networking task source once the resource has been fetched has been queued.
The img element is completely available.
The img element is broken.
Otherwise, the attribute must return false.
So essentially, complete returns true if the image has either finished loading, or failed to load. Since we want only the case where the image successfully loaded we need to check the nauturalHeight attribute as well:
The IDL attributes naturalWidth and naturalHeight must return the
intrinsic width and height of the image, in CSS pixels, if the image
is available, or else 0.
And available is defined like so:
An img is always in one of the following states:
Unavailable - The user agent hasn't obtained any image data.
Partially available - The user agent has obtained some of the image data.
Completely available - The user agent has obtained all of the image data and at least the image dimensions are available.
Broken - The user agent has obtained all of the image data that it can, but it cannot even decode the image enough to get the image
dimensions (e.g. the image is corrupted, or the format is not
supported, or no data could be obtained).
When an img element is either in the partially available state or in
the completely available state, it is said to be available.
So if the image is "broken" (failed to load), then it will be in the broken state, not the available state, so naturalHeight will be 0.
Therefore, checking imgElement.complete && imgElement.naturalHeight !== 0 should tell us whether the image has successfully loaded.
You can read more about this in the W3C HTML Specification for the img element, or on MDN.
I tried many different ways and this way is the only one worked for me
//check all images on the page
$('img').each(function(){
var img = new Image();
img.onload = function() {
console.log($(this).attr('src') + ' - done!');
}
img.src = $(this).attr('src');
});
You could also add a callback function triggered once all images are loaded in the DOM and ready. This applies for dynamically added images too. http://jsfiddle.net/kalmarsh80/nrAPk/
Use imagesLoaded javascript library.
Usable with plain Javascript and as a jQuery plugin.
Features:
officially supported by IE8+
license: MIT
dependencies: none
weight (minified & gzipped) : 7kb minified (light!)
Resources
Project on github: https://github.com/desandro/imagesloaded
Official website: http://imagesloaded.desandro.com/
https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load
imagesloaded javascript library: what is the browser & device support?
Retrieve informations from image elements on the page
Test working on Chrome and Firefox
Working jsFiddle (open your console to see the result)
$('img').each(function(){ // selecting all image element on the page
var img = new Image($(this)); // creating image element
img.onload = function() { // trigger if the image was loaded
console.log($(this).attr('src') + ' - done!');
}
img.onerror = function() { // trigger if the image wasn't loaded
console.log($(this).attr('src') + ' - error!');
}
img.onAbort = function() { // trigger if the image load was abort
console.log($(this).attr('src') + ' - abort!');
}
img.src = $(this).attr('src'); // pass src to image object
// log image attributes
console.log(img.src);
console.log(img.width);
console.log(img.height);
console.log(img.complete);
});
Note : I used jQuery, I thought this can be acheive on full javascript
I find good information here OpenClassRoom --> this is a French forum
After reading the interesting solutions on this page, I created an easy-to-use solution highly influenced by SLaks' and Noyo's post that seems to be working on pretty recent versions (as of writing) of Chrome, IE, Firefox, Safari, and Opera (all on Windows). Also, it worked on an iPhone/iPad emulator I used.
One major difference between this solution and SLaks and Noyo's post is that this solution mainly checks the naturalWidth and naturalHeight properties. I've found that in the current browser versions, those two properties seem to provide the most helpful and consistent results.
This code returns TRUE when an image has loaded fully AND successfully. It returns FALSE when an image either has not loaded fully yet OR has failed to load.
One thing you will need to be aware of is that this function will also return FALSE if the image is a 0x0 pixel image. But those images are quite uncommon, and I can't think of a very useful case where you would want to check to see if a 0x0 pixel image has loaded yet :)
First we attach a new function called "isLoaded" to the HTMLImageElement prototype, so that the function can be used on any image element.
HTMLImageElement.prototype.isLoaded = function() {
// See if "naturalWidth" and "naturalHeight" properties are available.
if (typeof this.naturalWidth == 'number' && typeof this.naturalHeight == 'number')
return !(this.naturalWidth == 0 && this.naturalHeight == 0);
// See if "complete" property is available.
else if (typeof this.complete == 'boolean')
return this.complete;
// Fallback behavior: return TRUE.
else
return true;
};
Then, any time we need to check the loading status of the image, we just call the "isLoaded" function.
if (someImgElement.isLoaded()) {
// YAY! The image loaded
}
else {
// Image has not loaded yet
}
Per giorgian's comment on SLaks' and Noyo's post, this solution probably can only be used as a one-time check on Safari Mobile if you plan on changing the SRC attribute. But you can work around that by creating an image element with a new SRC attribute instead of changing the SRC attribute on an existing image element.
Realtime network detector - check network status without refreshing the page:
(it's not jquery, but tested, and 100% works:(tested on Firefox v25.0))
Code:
<script>
function ImgLoad(myobj){
var randomNum = Math.round(Math.random() * 10000);
var oImg=new Image;
oImg.src="YOUR_IMAGELINK"+"?rand="+randomNum;
oImg.onload=function(){alert('Image succesfully loaded!')}
oImg.onerror=function(){alert('No network connection or image is not available.')}
}
window.onload=ImgLoad();
</script>
<button id="reloadbtn" onclick="ImgLoad();">Again!</button>
if connection lost just press the Again button.
Update 1:
Auto detect without refreshing the page:
<script>
function ImgLoad(myobj){
var randomNum = Math.round(Math.random() * 10000);
var oImg=new Image;
oImg.src="YOUR_IMAGELINK"+"?rand="+randomNum;
oImg.onload=function(){networkstatus_div.innerHTML="";}
oImg.onerror=function(){networkstatus_div.innerHTML="Service is not available. Please check your Internet connection!";}
}
networkchecker = window.setInterval(function(){window.onload=ImgLoad()},1000);
</script>
<div id="networkstatus_div"></div>
This is how I got it to work cross browser using a combination of the methods above (I also needed to insert images dynamically into the dom):
$('#domTarget').html('<img src="" />');
var url = '/some/image/path.png';
$('#domTarget img').load(function(){}).attr('src', url).error(function() {
if ( isIE ) {
var thisImg = this;
setTimeout(function() {
if ( ! thisImg.complete ) {
$(thisImg).attr('src', '/web/css/img/picture-broken-url.png');
}
},250);
} else {
$(this).attr('src', '/web/css/img/picture-broken-url.png');
}
});
Note: You will need to supply a valid boolean state for the isIE variable.
var isImgLoaded = function(imgSelector){
return $(imgSelector).prop("complete") && $(imgSelector).prop("naturalWidth") !== 0;
}
// Or As a Plugin
$.fn.extend({
isLoaded: function(){
return this.prop("complete") && this.prop("naturalWidth") !== 0;
}
})
// $(".myImage").isLoaded()
As I understand the .complete property is non-standard. It may not be universal... I notice it seem to work differently in Firefox verses IE. I am loading a number of images in javascript then checking if complete. In Firefox, this seems to work great. In IE, it doesn't because the images appear to be loading on another thread. It works only if I put a delay between my assignment to image.src and when I check the image.complete property.
Using image.onload and image.onerror isn't working for me, either, because I need to pass a parameter to know which image I am talking about when the function is called. Any way of doing that seems to fail because it actually seems to pass the same function, not different instances of the same function. So the value I pass into it to identify the image always ends up being the last value in the loop. I cannot think of any way around this problem.
On Safari and Chrome, I am seeing the image.complete true and the naturalWidth set even when the error console shows a 404 for that image... and I intentionally removed that image to test this. But the above works well for Firefox and IE.
This snippet of code helped me to fix browser caching problems:
$("#my_image").on('load', function() {
console.log("image loaded correctly");
}).each(function() {
if($(this).prop('complete')) $(this).load();
});
When the browser cache is disabled, only this code doesn't work:
$("#my_image").on('load', function() {
console.log("image loaded correctly");
})
to make it work you have to add:
.each(function() {
if($(this).prop('complete')) $(this).load();
});
Using this JavaScript code you can check image is successfully loaded or not.
document.onready = function(e) {
var imageobj = new Image();
imageobj.src = document.getElementById('img-id').src;
if(!imageobj.complete){
alert(imageobj.src+" - Not Found");
}
}
Try out this
I had a lot of problems with the complete load of a image and the EventListener.
Whatever I tried, the results was not reliable.
But then I found the solution. It is technically not a nice one, but now I never had a failed image load.
What I did:
document.getElementById(currentImgID).addEventListener("load", loadListener1);
document.getElementById(currentImgID).addEventListener("load", loadListener2);
function loadListener1()
{
// Load again
}
function loadListener2()
{
var btn = document.getElementById("addForm_WithImage"); btn.disabled = false;
alert("Image loaded");
}
Instead of loading the image one time, I just load it a second time direct after the first time and both run trough the eventhandler.
All my headaches are gone!
By the way:
You guys from stackoverflow helped me already more then hundred times. For this a very big Thank you!
This one worked fine for me :)
$('.progress-image').each(function(){
var img = new Image();
img.onload = function() {
let imgSrc = $(this).attr('src');
$('.progress-image').each(function(){
if($(this).attr('src') == imgSrc){
console.log($(this).parent().closest('.real-pack').parent().find('.shimmer').fadeOut())
}
})
}
img.src = $(this).attr('src');
});
I'm trying to dynamically preload list of files which may be anything between images and JavaScript files. Everything is going supersmooth with Chrome and Firefox, but failing when I'm trying to preload JavaScript files with Edge. Edge still can handle images for example but no js files. And yes I've tried with addEventListener, it's not working either.
Edge doesn't give me any errors.
var object = {};
object = document.createElement('object');
object.width = object.height = 0;
object.data = path/to/javascriptfile.js
body.appendChild(object);
object.onload = function(){
console.log('hello world')
//not firing with edge
}
Anything relevant I'm missing?
UPDATE: Didn't get any success after the day. Will probably leave it for now and just skip preloading script files with edge until i find a solution.
Perhaps worth a check - from msdn:
The client loads applications, embedded objects, and images as soon as
it encounters the applet, embed, and img objects during parsing.
Consequently, the onload event for these objects occurs before the
client parses any subsequent objects. To ensure that an event handler
receives the onload event for these objects, place the script object
that defines the event handler before the object and use the onload
attribute in the object to set the handler.
https://msdn.microsoft.com/en-us/library/windows/apps/hh465984.aspx
Edit, a clarification:
You should attach the event listener before the element is added to the page.
Even doing that I'm not sure if it'll work or not though. But to make sure you've exhausted all options try the example below:
function doLoad() {
console.log('The load event is executing');
}
var object = {};
object = document.createElement('object');
object.width = object.height = 0;
object.data = 'path/to/javascriptfile.js';
object.onreadystatechange = function () {
if (object.readyState === 'loaded' || object.readyState === 'complete') doLoad();
console.log('onreadystatechange');
}
if (object.addEventListener) {
object.addEventListener( "load", doLoad, false );
console.log('addEventListener');
}
else
{
if (object.attachEvent) {
object.attachEvent( "onload", doLoad );
console.log('attachEvent');
} else if (object.onLoad) {
object.onload = doLoad;
console.log('onload');
}
}
var body = document.getElementsByTagName("body")[0];
body.appendChild(object);
If this doesn't work, you could perhaps preload using "image" instead of "object" in IE: https://stackoverflow.com/a/11103087/1996783
Working temporary solution is to put onload event directly to script element instead of object. It's sad since it works like a charm in Chrome & FF.
It turns out, object.data with css source did not load either. I don't know if it's a bug since it still can load image from to object.data.
But show must go on.
Cheers, eljuko
I'm using IE Edge's emulator mode to test some work and one of the project I work on requires IE8. The emulator is pretty useful to debug some stuff that the original IE8 is doing a good job at blackboxing. I'm trying to find a way around this bug since Microsoft isn't willing to fix it.
The problem is that IE8 emulator hangs on SVG image load. I'm currently using this SVG fallback library which works great on the real IE8 but I was wondering if there is a way to modify events or object prototypes using Javascript to change the behavior of the browsers before it tries to load SVG images when parsing HTML? Is there such a way to solve this issue or should I just live with this bug? I have this dirty workaround which does the trick but I'm hoping to find a more proactive solution.
var fixMySVG = setInterval(function () {
var elements = document.getElementsByTagName('img');
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.src = element.src.replace(/^(.+)(\.svg)(\?.)*$/ig, '$1.' + 'png' + '$3');
}
if (document.readyState == 'complete') {
clearInterval(fixMySVG);
}
}, 100);
There is no error, the image is just stuck in an 'uninitialized' state (so I cannot use the onerror event). I'm also unaware of any onbeforeoload event I could use.
Is using interval the only solution?
Edit
I realize there is no perfect solution but to solve basic <img> and backgroundImage style, using interval seems to do an good job without performance hit. On top of that fall back images seems to load faster. I updated my SVG fallback to use interval instead of using onload events which solve both IE8 emulator and the real IE8.
It's a really odd bug, since there is no older-version emulation mode in Edge, just mobile one and user-agent string emulation, which will just allow you "to debug errors caused by browser sniffing", but in no way it is related to some feature non-support.
Using your fallback is one out of many options but there is no "clean" way to do this. On top of that it will not solve SVG images using <object>, <iframe> or <embded> elements, nor inline <svg> elements.
So this doesn't point directly to your issue, which should be fixed by IE team since it's a bug in their browser, but just for the hack, here is a way to change the src of an image before the fetching of the original one starts.
Disclaimer
Once again, this is a hack and should not be used in any production nor development site maybe just for an edge debugging case like yours and for experimentation but that's all !
Note : this will work in modern browsers, including Edge with IE8 user-string Emulation set, but not in the original IE8.
Before the dump
This code should be called in the <head> of your document, preferably at the top-most, since everything that is called before it will be called twice.
Read the comments.
<script id="replaceSrcBeforeLoading">
// We need to set an id to the script tag
// This way we can avoid executing it in a loop
(function replaceSrcBeforeLoading(oldSrc, newSrc) {
// first stop the loading of the document
if ('stop' in window) window.stop();
// IE didn't implemented window.stop();
else if ('execCommand' in document) document.execCommand("Stop");
// clear the document
document.removeChild(document.documentElement);
// the function to rewrite our actual page from the xhr response
var parseResp = function(resp) {
// create a new HTML doc
var doc = document.implementation.createHTMLDocument(document.title);
// set its innerHTML to the response
doc.documentElement.innerHTML = resp;
// search for the image you want to modify
// you may need to tweak it to search for multiple images, or even other elements
var img = doc.documentElement.querySelector('img[src*="' + oldSrc + '"]');
// change its src
img.src = newSrc;
// remove this script so it's not executed in a loop
var thisScript = doc.getElementById('replaceSrcBeforeLoading');
thisScript.parentNode.removeChild(thisScript);
// clone the fetched document
var clone = doc.documentElement.cloneNode(true);
// append it to the original one
document.appendChild(clone);
// search for all script elements
// we need to create new script element in order to get them executed
var scripts = Array.prototype.slice.call(clone.querySelectorAll('script'));
for (var i = 0; i < scripts.length; i++) {
var old = scripts[i];
var script = document.createElement('script');
if (old.src) {
script.src = old.src;
}
if (old.innerHTML) {
script.innerHTML = old.innerHTML;
}
old.parentNode.replaceChild(script, old);
}
}
// the request to fetch our current doc
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && (this.status == 200 || this.status == 0)) {
var resp = this.responseText || this.response;
parseResp(resp);
}
};
xhr.open('GET', location.href);
xhr.send();
})('oldSrc.svg',
'newSrc.svg');
</script>
And a live example which won't work with the IE8 UA string since plnkr.co just doesn't allow this browser on his website :-/
I need to perform some re-calculations after disqus form gets an update. A new comment, error message just to name a few. In essence any event that causes the Disqus iframe to expand vertically. Checked the API, but didn't find any public events. Seems like the events are not publicly accessibly atm. So the first question is – does Disqus have any public events to attach to?
The second would be – if I have no way to attach to events from Disqus I wonder would MutationEvent do the trick for me taking into account that Disqus stuff is within an iFrame?
Best I have come up with so far
function disqus_config() {
this.callbacks.onNewComment = [function() { trackComment(); }];
}
from here:
http://help.disqus.com/customer/portal/articles/466258-how-can-i-capture-disqus-commenting-activity-in-my-own-analytics-tool-
Doing a console.log(DISQUS) in the chrome console shows the disqus object, and there are other callbacks mentioned
_callbacks: Object
switches.changed: Array[2]
window.click: Array[2]
window.hashchange: Array[2]
window.resize: Array[2]
window.scroll: Array[2]
and on and trigger methods
I'm not sure about public events for Disqus in particular, but if you just need to monitor changes to an iframe's height, here's one way:
var iframe = document.getElementById('myIframe');
var iframeHeight = iframe.clientHeight;
setInterval(function() {
if(iframe.clientHeight != iframeHeight) {
// My iframe's height has changed - do some stuff!
iframeHeight = iframe.clientHeight;
}
}, 1000);
Granted, it's basically a hack. But it should work!
Well, they don't have any public events documented (as far I can tell). But, application is triggering a lot of events on its parent window. So it's possible to listen to them and make some actions. You can do that with following snippet:
window.addEventListener('message', function (event) {
// if message is not from discus frame, leap out
if (event.origin != 'https://disqus.com' && event.origin != 'http://disqus.com') return;
// parse data
var data = JSON.parse(event.data);
// do stuff with data. type of action can be detected with data.name
// property ('ready', 'resize', 'fakeScroll', etc)
}, false);
In webkit based browsers it works just fine. With firefox there might be some issues. With IE... well, I don't have any IE on hand to test it.
You can find list of available events in embed payload:
callbacks:{
preData:[],
preInit:[],
onInit:[],
afterRender:[],
onReady:[],
onNewComment:[],
preReset:[],
onPaginate:[],
onIdentify:[],
beforeComment:[]
}
I haven't found any documentation (except example for onNewComment), so you need guess how they works from event name.
You can use them in this way:
var disqus_config = function () {
this.callbacks.onNewComment = [
function() {
// your code
}
];
};
or
var disqus_config = function () {
this.callbacks.onNewComment = this.callbacks.onNewComment || [];
this.callbacks.onNewComment.push(function() {
// your code
});
}
On the side note, I found them completely useless for detecting change in height of comments iframe. I ended with using ResizeSensor from css-element-queries.
This is sufficiently important to me that I'm opening the question up to a bounty with a simple goal: Can anyone successfully open a new, full-screen NativeWindow in AJAX Air and, from that window, detect key strokes?
Hopefully I'm just overlooking something really, really simple, but if JS is not capable of listening for keyboard events, maybe a flash widget/helper might be able to relay keyboard events to JS. That's the only thing I can think of, but there may be other ways. I just don't know. Hopefully someone out there knows the right answer!
Update
Many thanks to #mwilcox for the answer. I don't know what the difference is between the method I was using (from the O'Reilly Cookbook) and createRootWindow(), but whatever it is, it did solve my problems. The code I ended up using is this:
var objWindowOptions = new air.NativeWindowInitOptions();
objWindowOptions.transparent = false;
objWindowOptions.systemChrome = air.NativeWindowSystemChrome.STANDARD;
objWindowOptions.type= air.NativeWindowType.NORMAL;
var linkScreenToMainWindow = function() {
wWindow.removeEventListener(air.Event.COMPLETE,linkScreenToMainWindow);
objScreen.setWindowReference(wWindow.stage.getChildAt(0).window);
// At this point your windows are connected and you can fire commands into
// the window using objScreen as a proxy. For example:
alert(objScreen.document.body.innerHTML);
objScreen.myfunction();
};
var fhFilePath = air.File.applicationDirectory.resolvePath('childwindow.html');
wWindow = air.HTMLLoader.createRootWindow(true, objWindowOptions, true);
wWindow.stage.displayState = window.runtime.flash.display.StageDisplayState.FULL_SCREEN_INTERACTIVE;
wWindow.addEventListener(air.Event.COMPLETE,linkScreenToMainWindow);
wWindow.load(new air.URLRequest(fhFilePath.url));
I've created a new window in Adobe Air (JS) and I need to capture any key-presses (or keydowns if it's easier). I have no problem adding an event listener to the main window, but any child window doesn't seem to recognize any of the common hook techniques.
Part of the problem, I think, is that the first parameter of addEventListener() is the name of the event, and all of the documented event names fail to raise any events. Any idea what how I'm supposed to do this?
Main window
// Keyboard handler and event listener subscription:
var watcher = function() {
alert("Working");
};
window.addEventListener("keypress",watcher,false); // WORKS!
// Create child window:
var wWindow = new air.NativeWindow(objWindowOptions);
wWindow.activate();
wWindow.stage.displayState = window.runtime.flash.display.StageDisplayState.FULL_SCREEN_INTERACTIVE;
wWindow.stage.scaleMode = "noScale";
wWindow.stage.addChild( htmlView );
htmlView.load( new air.URLRequest("newpage.html") );
Child window: newpage.html
// Keyboard handler and event listener subscription
var handler = function() {
alert('success!');
};
var strEventName = KeyboardEvent.KEY_DOWN; // Fails -- is undefined
//var strEventName = KeyboardEvent.KEYDOWN; // Fails -- is undefined
//var strEventName = 'keydown'; // Fails
// var strEventName = 1024; // Fails
window.nativeWindow.stage.addEventListener(strEventName,handler,false); // Fails
nativeApplication.addEventListener(strEventName,handler,false); // Fails
window.addEventListener(strEventName,handler,false); // Fails
I may be mistaken, but I think I've tried every permutation of the above and none of them work.
I think you're missing a step. Try:
var newWin = air.HTMLLoader.createRootWindow(...options);
var container = newWin.window.nativeWindow;
Otherwise, are you sure AIR is loaded in that child window?