Trouble refreshing iframe with javascript - javascript

This used to work, but for some reason it doesn't anymore. I use a javascript to change the source of an iframe and then refresh it. The reason is I want to send a variable into the iframe before it is viewed.
I added som debug code, and it shows "debug 1" but not "debug 2".
What might be the issue?
$("#upload_iframe").attr("src", "/editor/upload/?dir=" + dir);
// ---------------------------------
// THESE LINES DON'T WORK - STOPS AFTER FIRST DEBUG IS RUN...
// ---------------------------------
alert('debug 1');
$("#upload_iframe").contentWindow.location.reload(true);
alert('debug 2');
// ---------------------------------
$("#upload_file").dialog('open');

As you want to access the dom and not the jquery object you should add [0] :
$("#upload_iframe") //is an array of matching dom objects
$("#upload_iframe")[0] //is the first matching dom object
You might also add a random string to prevent browser caching:
$("#upload_iframe")[0].contentWindow.location.href = "/editor/upload/?dir=" + dir + "&rid=" + Math.random();

Personally, I've not had much luck using the "reload()" method. Try this:
$("#upload_iframe").contentWindow.location.href = $("#upload_iframe").contentWindow.location.href;

Related

Detecting net::ERR_FILE_NOT_FOUND with only JS

I have recreated a blueprint, which has 60+ rooms, as an inline SVG.
There are functions that display information, such as pictures, when you select or hover a room. I'm using one div container to display the pictures by setting its background property to url('path-of-image.ext'), as can be seen below.
var cla = document.getElementsByClassName('cla');
for (i = 0; i < cla.length; i++) {
cla[i].addEventListener('mouseenter', fun);
}
function fun(){
var str = 'url("media/' + this.id.slice(4) + '.jpg")';
pictureFrame.style.background = str;
pictureFrame.style.backgroundSize = 'cover';
pictureFrame.style.backgroundPosition = 'center'
}
The reason I'm not using the background property's shorthand is because I plan on animating the background-position property with a transition.
However, not all rooms have pictures. Hence console throws the following error, GET ... net::ERR_FILE_NOT_FOUND, when you select or hover said rooms. The error doesn't cause the script to break, but I would prefer not to run that code every single time a room is hovered, even when a given room doesn't have pictures.
Even though I know this can be done imperatively with if/else statements, I'm trying to do this programmatically since there are so many individual rooms.
I've tried using try/catch, but this doesn't seem to detect this sort of error.
Any ideas?
Is it even possible to detect this kind of error?
You could attempt to read it using FileReader and catch/handle NotFoundError error.
If it were to error, you could assign it to an object or array which you would first check upon hover. If the file was in that array, you could avoid attempting to read it again and just handle however you like.
Here is a good article by Nicholas Zakas on using FileReader
First off I would see if there is a way of checking if the file exists before the document even loads so that you don't make unnecessary requests. If you have a database on the backend which can manage this that would serve you very well in the long term
Since you make it sound like the way you only know a file exists is by requesting it, here's a method that will allow you to try this:
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
This won't request the image twice because of browser caching. As you can see that method is itself being depricated and overall the best way you can remedy this problem is checking before the page even loads; if you have a database or datastructure of any sort, add a class or property to the element if the image exists or not. Then, in your existing method, you can call something like document.getElementsByClassName('cla-with-image') to get only records that you've determined has an image (much more efficient than trying to load images that don't exist).
If you end up using that UrlExists method, then you can just modify your existing method to be
function fun(){
var url = "media/' + this.id.slice(4) + '.jpg";
if (UrlExists(url)) {
var str = 'url(' + url + ')';
pictureFrame.style.background = str;
pictureFrame.style.backgroundSize = 'cover';
pictureFrame.style.backgroundPosition = 'center'
}
}

Phantomjs not clicking element properly

I want to scrape this web page with phantomjs:
http://www1.macys.com/shop/product/john-ashford-shirt-long-sleeve-solid-rugby-polo?ID=875571&CategoryID=20640&LinkType=PDPZ1
and, for each color, get the available sizes. I think this requires .select()ing each color, waiting for a bit, and checking which sizes have class=disabledOption. Right now I have something that looks like this:
get_colors_for_size = (index, color_elem, item_id) ->
$(color_elem).select()
setTimeout(->
size_selector = "#sizeList"+item_id+" > li"
$(size_selector).each (index, size_elem) ->
size_name = size_elem.title
if not $(size_elem).hasClass("disabledOption")
console.log($(color_elem).title + " " + size_name)
#sizes_for_color.push(size_name)
, 500)
$(color_selector).each (index, color_elem) ->
color_name = color_elem.title
console.log(color_name)
interval = 1000*index
console.log(interval)
setTimeout(->
get_colors_for_size(index, color_elem, item_id)
, interval)
, item_id, get_colors_for_size
However, there's two problems:
1) I don't think the color elements are being selected properly (I've also tried click() on them and all their children), since I'm getting the same size options returned for each color
2) This is really ugly and might suffer from race conditions.
Is there another way to execute a blocking workflow, e.g. pause this js execution to wait for other js to execute?
this bug might help? I encountered a similar issue that I was unable to click a link by executing jquery.
https://github.com/detro/ghostdriver/issues/355#

Can't change dconf-entry with GSettings

I'm currently building a simple application on Gjs, which should change the background-image of my gnome-shell. A solution on how this can be done using the gsettings-tool can be found here.
Since I want to build a desktop-application around it, I want to change the org.gnome.desktop.background.picture-uri-key by using Gio's GSettings-class. But using the set_X()-method does not change the value of the key.
This is my code to change the gsettings value:
var gio = imports.gi.Gio;
// Get the GSettings-object for the background-schema:
var background = new gio.Settings({schema: "org.gnome.desktop.background"});
// Read the current Background-Image:
print( "Current Background-Image: "+background.get_string("picture-uri") );
if (background.is_writable("picture-uri")){
// Set a new Background-Image (should show up immediately):
if (background.set_string("picture-uri", "file:///path/to/some/pic.jpg")){
print("Success!");
}
else throw "Couldn't set the key!";
} else throw "The key is not writable";
Reading the value does work as expected, the is_writable()-method returns true and the set_string()-method also returns true.
I have checked that I'm not in "delay-apply" mode and the key has a GVariantType of string, so the set_string()-method should work.
Using the normal gsettings command-line tool (as explained in the linked post) works just fine.
I can't figure out what the problem is, is there any place I can look for logs or something?
After not getting any responses here I asked the same question on the gjs-mailing list.
It turned out that the writes to dconf were not yet on the disk when my script exited, so they were never really applied.
The solution was to call the g_settings_sync() function (JsDoc) right after the set_string() function, to ensure that all writes had finished.
if (background.set_string("picture-uri", "file:///path/to/some/pic.jpg")){
gio.Settings.sync()
print("Success!");
}
Thanks to Johan Dahlin and his answer.

Extending DOMWindow object

I'm a total JavaScript/jQuery n00b, so please forgive me in advance.
Imagine there's a webpage (W1) which displays a list of items (I1, I2, ...). Now there's a second webpage W2 which displays W1 in a FancyBox'ed iframe (<a class="iframe" href="addressof(W1)">Pick items</a>).
Each item inside a W1 has a JavaScript handler attached to its click event, which does this:
function SetOpenerClient(id, name,isHoldings)
{
var _hfBackPath = document.getElementById('ctl00_main_hfBackPath');
var url = _hfBackPath.value;
window.navigate(url +"?id="+id+"&name="+name+"&isHol="+isHoldings);
}
The usual way this whole mess is used is by window.open()ing a window and providing a "backpath":
window.open(addressof(W1) + "?backpath=" + addressOfHandlerThisWebSite,
"selectClient",
"status=no,toolbar=no,menubar=no,location=no,scrollbars=yes")
Now here's whay my investigations show. Whenever a user click on an item inside of W1, it niavigates back to backpath (_hfBackPath from SetOpenerClient()), which happens to be a specially crafted page which grabs id querystring parameter, stuffs it inside a Session and does all kinds of other stuff.
When W1 gets opened inside an iframe, Chrome complains:
Uncaught TypeError: Object [object DOMWindow] has no method 'navigate'
Here's whay I want (by the way, there's $50 bill glued under your chair) and I really hope this is possible. I want to "redefine" window.navigate method to so that I could handle item selection manually. Is this possible? My naive attempts of setting
DOMWindow.navigate = function () { alert("window.navigate"); };
apparently don't do anything.

Determining creation date of an image in Javascript?

I'm attempting to create a page that displays and refreshes an image from a webcam (camimg.jpg), but displays a static image (notlive.jpg) if the image hasn't been updated recently. I've found the AJAXCam script, which serves the purpose of reloading the "live" image at a set interval (15 secs), yet with no Javascript experience I can't figure out how to determine when the image was last updated in order to decide whether or not camimg.jpg or notlive.jpg should be displayed.
My limited experience with programming has me thinking it should be something along the lines of:
pageLoaded = time page loaded in browser
imageUpdated = time the image was uploaded to server
if imageUpdated is not within 20 seconds of pageLoaded:
display notlive.jpg
else:
run AJAXCam
The AJAXCam code (initially called by <body onLoad="holdUp()">) is as follows:
<script type="text/javascript">
<!--
//
//AJAXCam v0.8b (c) 2005 Douglas Turecek http://www.ajaxcam.com
//
function holdUp()
{
//
// This function is first called either by an onLoad event in the <body> tag
// or some other event, like onClick.
//
// Set the value of refreshFreq to how often (in seconds)
// you want the picture to refresh
//
refreshFreq=15;
//
//after the refresh time elapses, go and update the picture
//
setTimeout("freshPic()", refreshFreq*1000);
}
function freshPic()
{
//
// Get the source value for the picture
// e.g. http://www.mysite.com/doug.jpg and
//
var currentPath=document.campic.src;
//
// Declare a new array to put the trimmed part of the source
// value in
//
var trimmedPath=new Array();
//
// Take everything before a question mark in the source value
// and put it in the array we created e.g. doug.jpg?0.32234 becomes
// doug.jpg (with the 0.32234 going into the second array spot
//
trimmedPath=currentPath.split("?");
//
// Take the source value and tack a qustion mark followed by a random number
// This makes the browser treat it as a new image and not use the cached copy
//
document.campic.src = trimmedPath[0] + "?" + Math.random();
//
// Go back and wait again.
holdUp();
}
// -->
</script>
Is what I'm trying to accomplish even possible? And if so, how would I go about implementing it? Thanks in advance for the help!
There is no way to do it in javascript.
Your only option is, in case you have access to server side languages like PHP you can send a simple HEAD request and check Last Modified header of the image then report it back to the browser via Ajax.

Categories