I'm trying to create a login widget in an iframe that can be used on a clients website. This iframe will be using jQuery, but I first wont to be able to check if the parent document has jQuery loaded, if not, load it.
I've tried several different techniques but none seem to wont to work, or decide to load the jQuery library twice.
Any help would be greatly appreciated.
This code block is within the page loaded inside the iframe, which refuses to co-operate.
<script>
var jQOutput = false;
function initjQuery() {
if (typeof(jQuery) == 'undefined'){
if (!jQOutput){
jQOutput = true;
var jScript = document.createElement('script');
jScript.setAttribute("type", "text/javascript");
jScript.setAttribute("src", "js/libs/jquery/jquery-min.js");
}
setTimeout("initjQuery()", 50);
} else {
$(function() {
$("#email").css({"background":"red"});
//visual aid to see if jQuery is loaded.
});
}
}
</script>
I just want to check and see if the parent to the iframe has loaded jQuery, and if not, load it myself, as I'll be using it to perform several tasks needed to complete the login proceedure.
Entented comment:
I dont think what you want to archive is posible because of same origin policy (Cross domain access via JavaScript) - look it op on Google... http://google.com/search?q=same+origin+policy
If you on the other hand dont violate the same origin policy you can archive what you want using something like this:
var parent = window.parent; // This refers to parent's window object
if ( parent && parent.jQuery ) { // Check to see if parent and parent.jQuery is truly
window.jQuery = parent.jQuery;
window.$ = parent.jQuery;
}
else {
// load jQuery here
}
The JavaScript code of your widget has to be divided into two parts. One of them would be loaded on a client's site. It would have permissions to access the DOM of the site: load jQuery if needed, create an iframe, etc. (Be especially careful with global variables there! Try not to use them at all since they can conflict with the code of the site.) Note that this part wouldn't have access to the DOM of the iframe. That's why you need the second part, which would be loaded inside of the iframe. You can use cross-domain techniques for the parts to exchange messages with each other. I'd advise you to check out the easyXDM library.
Related
I need to execute some scripts when all the resources on my domain and subdomain are loaded, so I did this:
$(window).load(function(){
// al my functions here...
}
The problem is that there are some external resources (not on my domain and subdomain) that sometimes take longer to load. Is there a way to exclude external resources from the load event?
EDIT:
I was hoping to do something like:
$(window).not(".idontcare").load(function()
but it's not working
I guess your external resources rely on a src attribute.
If so, in your page source code you could set the src attribute of the resources you don't want to wait for, not as src but as external_src.
Then you could easily do:
$(document).ready(function(){
$(window).load(function(){
// all your functions here...
});
$('[external_src]').each(function() {
var external_src = $(this).attr("external_src");
$(this).attr("src", external_src); // now it starts to load
$(this).removeAttr("external_src"); // keep your DOM clean
//Or just one line:
//$(this).attr("src", $(this).attr("external_src")).removeAttr("external_src");
});
});
This way the external resources should start loading as soon as just the DOM is ready, without waiting for the full window load.
I have almost same case. But in my case, I want to exclude all iframes that load content from another site (e.g. youtube, vimeo etc). Found a work around, so the scenario is hide 'src' attribute from all iframes when DOM is ready and put it back when window is finish load all another content.
(function($){
//DOM is ready
$(document).ready(function(){
var frame = $('iframe'),
frameSrc = new Array();
if( frame.length ){
$.each( frame, function(i, f){
frameSrc[i] = $(f).attr('src');
//remove the src attribute so window will ignore these iframes
$(f).attr('src', '');
});
//window finish load
$(window).on('load',function(){
$.each( frame, function(a, x){
//put the src attribute value back
$(x).attr('src', frameSrc[a]);
});
});
}
});
})(jQuery);
You can mark all elements in your site that load external resources by adding a special class, and change the iframe with $('.special_class') or something like that. I dont know if this is the best way but at least it works great in my side :D
Unfortunately, the window.onload event is very strict. As you might know it will fire when all und every resource was transfered and loaded, images, iframes, everything. So the quick answer to your question is no, there is no easy-to-use way to tell that event to ignore external resources, it makes no difference there.
You would need to handle that yourself, which could be a tricky thing according to how those resources are included and located. You might even need to manipulate the source code before it gets delivered to accomplish that.
As far as I know, there is an async - tag for script tags. You can your includes to:
<script src="script_path" async="true"></script>
This will not include them to the event.
maybe
$(document).ready(...)
instead of $(window).load() will help?
The document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet.
What is the best unobtrusive way of invoking something after the page is being loaded in plain JavaScript? Of course in jQuery I would use:
$(document).ready(function(){...});
but I am not sure about the most reliable approach in plain js.
Clearly
window.onload = ...
is not proper solution, because it would overwrite previous declaration.
What I am trying to do is to insert an iframe into a div after the page is loaded, but maybe there are actually better ways of doing it. My plan is to do something like:
window.onload = function(divId){
var div = document.getElementById(divId);
div.innerHTML = "<iframe src='someUrl' .. >";
}
EDIT:
Apologies for not including all necessary details.
The script is not for my website - the idea is to show a part of my site (a form) on external web sites. The priority is to minimize the effort someone has to put to use my code. That is why I would like to keep everything in js file and absolutely nothing in <script> - except of <script src="http://my.website/code.js" />. If I change URL of an iframe or I would like to add some features, I would like to update the code on all other web sites without asking them to make any changes.
My approach might be wrong - any suggestions are very welcome.
//For modern browsers:
document.addEventListener( "DOMContentLoaded", someFunction, false );
//For IE:
document.attachEvent( "onreadystatechange", someFunction);
`attachEvent` and `addEventListener` allow you to register more than one event listener for a particular target.
See:
https://developer.mozilla.org/en/DOM/element.addEventListener
Also definitly worth looking at how jQuery does it:
http://code.jquery.com/jquery-1.7.js Search for bindReady.
Use window.addEventListener and the events load or DOMContentLoaded:
window.addEventListener('DOMContentLoaded',function(){alert("first handler");});
window.addEventListener('DOMContentLoaded',function(){alert("second handler");});
object.addEventListener('event',callback) will insert an event listener into a queue for that specific object event. See https://developer.mozilla.org/en/DOM/element.addEventListener for further information.
For IE5-8 use window.attachEvent('event',callback), see http://msdn.microsoft.com/en-us/library/ms536343%28VS.85%29.aspx. You can build yourself a little helper function:
function addEventHandler(object,szEvent,cbCallback){
if(typeof(szEvent) !== 'string' || typeof(cbCallback) !== 'function')
return false;
if(!!object.addEventListener){ // for IE9+
return object.addEventListener(szEvent,cbCallback);
}
if(!!object.attachEvent){ // for IE <=8
return object.attachEvent(szEvent,cbCallback);
}
return false;
}
addEventHandler(window,'load',function(){alert("first handler");});
addEventHandler(window,'load',function(){alert("second handler");});
Note that DOMContentLoaded isn't defined in IE lesser 9. If you don't know your recipient's browser use the event load.
Just put your script include at the very end of the document, immediately before or after the ending </body> tag, e.g.:
(content)
(content)
<script src="http://my.website/code.js"></script>
</body>
</html>
All of the markup above the script will be accessible via the usual DOM methods (reference). Obviously, not all ancillary resources (images and such) will be fully loaded yet, but presumably that's why you want to avoid the window load event (it happens so late).
The only real purpose of ready-style events is if you don't control where the script gets included (e.g., libraries) or you need to have something execute prior to the page load and something else after the page load, and you want to avoid having two HTTP requests (e.g., for two different scripts, one before load and one after).
I am trying to load Skyscanner API dynamically but it doesn't seem to work. I tried every possible way I could think of and all it happens the content disappears.
I tried console.log which gives no results; I tried elements from chrome's developers tools and while all the content's css remains the same, still the content disappears (I thought it could be adding display:none on the html/body sort of). I tried all Google's asynch tricks, yet again blank page. I tried all js plugins for async loading with still the same results.
Skyscanner's API documentation is poor and while they offer a callback it doesn't work the way google's API's callback do.
Example: http://jsfiddle.net/7TWYC/
Example with loading API in head section: http://jsfiddle.net/s2HkR/
So how can I load the api on button click or async? Without the file being in the HEAD section. If there is a way to prevent the document.write to make the page blank or any other way. I wouldn't mind using plain js, jQuery or PHP.
EDIT:
I've set a bounty to 250 ontop of the 50 I had previously.
Orlando Leite answered a really close idea on how to make this asynch api load although some features doesn't work such as selecting dates and I am not able to set styling.
I am looking for an answer of which I will be able to use all the features so that it works as it would work if it was loading on load.
Here is the updated fiddle by Orlando: http://jsfiddle.net/cxysA/12/
-
EDIT 2 ON Gijs ANSWER:
Gijs mentioned two links onto overwriting document.write. That sounds an awesome idea but I think it is not possible to accomplish what I am trying.
I used John's Resig way to prevent document.write of which can be found here: http://ejohn.org/blog/xhtml-documentwrite-and-adsense/
When I used this method, I load the API successfuly but the snippets.js file is not loading at all.
Fiddle: http://jsfiddle.net/9HX7N/
I belive what you want is it:
function loadSkyscanner()
{
function loaded()
{
t.skyscanner.load('snippets', '1', {'nocss' : true});
var snippet = new t.skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
}
var t = document.getElementById('sky_loader').contentWindow;
var head = t.document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange= function() {
if(this.readyState == 'complete') loaded();
}
script.onload= loaded;
script.src= 'http://api.skyscanner.net/api.ashx?key=PUT_HERE_YOUR_SKYSCANNER_API_KEY';
head.appendChild(script);
}
$("button").click(function(e)
{
loadSkyscanner();
});
It's load skyscanner in iframe#sky_loader, after call loaded function to create the SearchPanelControl. But in the end, snippet draws in the main document. It's really a bizarre workaround, but it works.
The only restriction is, you need a iframe. But you can hide it using display:none.
A working example
EDIT
Sorry guy, I didn't see it. Now we can see how awful is skyscanner API. It puts two divs to make the autocomplete, but not relative to the element you call to draw, but the document.
When a script is loaded in a iframe, document is the iframe document.
There is a solution, but I don't recommend, is really a workaround:
function loadSkyscanner()
{
var t;
this.skyscanner;
var iframe = $("<iframe id=\"sky_loader\" src=\"http://fiddle.jshell.net/orlleite/2TqDu/6/show/\"></iframe>");
function realWorkaround()
{
var tbody = t.document.getElementsByTagName("body")[0];
var body = document.getElementsByTagName("body")[0];
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
}
function snippetLoaded()
{
skyscanner = t.skyscanner;
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
setTimeout( realWorkaround, 2000 );
}
var loaded = function()
{
console.log( "loaded" );
t = document.getElementById('sky_loader').contentWindow;
t.onLoadSnippets( snippetLoaded );
}
$("body").append(iframe);
iframe.load(loaded);
}
$("button").click(function(e)
{
loadSkyscanner();
});
Load a iframe with another html who loads and callback when the snippet is loaded. After loaded create the snippet where you want and after set a timeout because we can't know when the SearchPanelControl is loaded. This realWorkaround move the autocomplete divs to the main document.
You can see a work example here
The iframe loaded is this
EDIT
Fixed the bug you found and updated the link.
the for loop has gone and added a while, works better now.
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
For problematic cases like this, you can just overwrite document.write. Hacky as hell, but it works and you get to decide where all the content goes. See eg. this blogpost by John Resig. This ignores IE, but with a bit of work the trick works in IE as well, see eg. this blogpost.
So, I'd suggest overwriting document.write with your own function, batch up the output where necessary, and put it where you like (eg. in a div at the bottom of your <body>'). That should prevent the script from nuking your page's content.
Edit: OK, so I had/took some time to look into this script. For future reference, use something like http://jsbeautifier.org/ to investigate third-party scripts. Much easier to read that way. Fortunately, there is barely any obfuscation/minification at all, and so you have a supplement for their API documentation (which I was unable to find, by the way -- I only found 'code wizards', which I had no interest in).
Here's an almost-working example: http://jsfiddle.net/a8q2s/1/
Here's the steps I took:
override document.write. This needs to happen before you load the initial script. Your replacement function should append their string of code into the DOM. Don't call the old document.write, that'll just get you errors and won't do what you want anyway. In this case you're lucky because all the content is in a single document.write call (check the source of the initial script). If this weren't the case, you'd have to batch everything up until the HTML they'd given you was valid and/or you were sure there was nothing else coming.
load the initial script on the button click with jQuery's $.getScript or equivalent. Pass a callback function (I used a named function reference for clarity, but you can inline it if you prefer).
Tell Skyscanner to load the module.
Edit #2: Hah, they have an API (skyscanner.loadAndWait) for getting a callback once their script has loaded. Using that works:
http://jsfiddle.net/a8q2s/3/
(note: this still seems to use a timeout loop internally)
In the skyrunner.js file they are using document.write to make the page blank on load call back... So here are some consequences in your scenario..
This is making page blank when you click on button.
So, it removes everything from page even 'jQuery.js' that is why call back is not working.. i.e main function is cannot be invoked as this is written using jQuery.
And you have missed a target 'div' tag with id = map(according to the code). Actually this is the target where map loads.
Another thing i have observed is maps is not actually a div in current context, that is maps api to load.
Here you must go with the Old school approach, That is.. You should include your skyrunner.js file at the top of the head content.
So try downloading that file and include in head tag.
Thanks
A 3rd party script on my web page creates an iframe. I need to know when this iframe is ready, so I can manipulate its DOM.
I can think of a hacky approach: repeatedly try to modify the iFrame's DOM, and return success when a change we make sticks between two attempts. For this to work, I would prefer a property I can check on the iframe repeatedly.
Is there an alternative, cross-browser evented approach to knowing that the iframe is ready? E.g. can we redefine the onLoad function to call into our code (but I don't know if I can do this, since I didn't create the iframe).
using jquery?
function callIframe(url, callback) {
$(document.body).append('<IFRAME id="myId" ...>');
$('iframe#myId').attr('src', url);
$('iframe#myId').load(function()
{
callback(this);
});
}
Question answered in jQuery .ready in a dynamically inserted iframe
Have a variable in the parent:
var setToLoad = false;
Follow it up with a function to set it:
function SetToLoad() {
setToLoad = true;
}
Then in the child iframe call this function using the window.opener
function CallSetToLoad() {
window.opener.SetToLoad();
}
window.onload = CallSetToLoad;
This won't run until the iframe is finished loading, and if it's in the same domain it'll allow access to the opener. This would require editing a small portion of the 3rd party script.
EDIT: Alternative solution
Given that you can't edit the script, you might try something like:
frames["myiframe"].onload = function()
{
// do your stuff here
}
Can you inject arbitrary scripting code into your iframe? If so, you should be able to make it so that some code executes in the iframe upon the the iframe loading that calls code in the parent page.
First: You probably won't be able to manipulate its dom when it loads html from other domain
And You probably are interested in DOMready.
Look here:
jQuery .ready in a dynamically inserted iframe
Bilal,
There's a document.readyState property that you can check (works in IE).
foo(){
if([your iframe id].document.readyState != "complete")
{
setTimeout("foo()", 500); //wait 500 ms then call foo
}
else
{
//iframe doc is ready
}
}
Arkady
I'm looking for a light weight method for client-side includes of HTML files. In particular, I want to enable client-side includes of publication pages of researchr.org, on third party web pages. For example, I'd like to export a page like
http://researchr.org/profile/eelcovisser/publications
(probably just the publications box of that page.)
Using an iframe it is possible to include HTML pages:
<iframe class="foo" style="height: 50em;" width="100%" frameborder="0"
src="http://researchr.org/profile/eelcovisser/publications">
</iframe>
However, iframes require specification of a fixed height, while the pages I'm exporting don't have a fixed height. The result has an ugly scrollbar:
http://swerl.tudelft.nl/bin/view/EelcoVisser/PublicationsResearchr
I found one reference to a method that appears to be appealing
http://www.webdeveloper.com/forum/archive/index.php/t-26436.html
It uses an iframe to import the html, and then a javascript call from the included document to a function defined in the including document, which places the contents of the body of the included file in a div of the including file. This does not work in my scenario, probably due to the same origin policy for javascript, i.e. the including and included page are not from the same domain (which is the whole point).
Any ideas for solving this? Which could be either:
a CSS trick to make the height of the iframe flexible
a javascript technique to lift the contents of the iframe to a div in the including page
some other approach I've overlooked
Requirement: the code to include on should be minimal.
No. The same-origin policy prevents you from doing any of that stuff (and rightly). You will have to go server-side, have a script on your server access that page and copy its contents into your own page (prefeably at build-time/in the background; you could do it at access-time or via AJAX but that would involve a lot of scraping traffic between your server and theirs, which may not be appreciated.
Or just put up with the scrollbar or make the iframe very tall.
As far as I know there is no CSS trick, the only way is to query the iFrame's document.documentElement.offsetHeight or scrollHeight, depending on which is higher, take that value and apply it on the iframe's css height ( add the + 'px' ).
try this ajax with cross domain capability
Why don't you use AJAX?
Try this:
<div id="content"></div>
<script type="text/javascript">
function AJAXObj () {
var obj = null;
if (window.XMLHttpRequest) {
obj = new XMLHttpRequest();
} else if (window.ActiveXObject) {
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
return obj;
}
var retriever = new AJAXObj();
function getContent(url)
{
if (retriever != null) {
retriever.open('GET', url, true);
retriever.onreadystatechange = function() {
if (retriever.readyState == 4) {
document.getElementsById('content').innerHTML(retriever.responseText);
}
}
retriever.send(null);
}
}
getContent('http://researchr.org/profile/eelcovisser/publications');
</script>
And then, you can parse the received page content with JS with regular expressions, extracting whatever content you want from that page.
Edit:
Sorry, I guess I missed the fact that it's a different domain. But as ceejayoz said, you could use a proxy for that.
If you're using jQuery, you can use the load method to retrieve a page via AJAX, optionally scrape content from it, and inject it into an existing element. The only problem is that it requires JavaScript.