I'm currently working on an iframe for clients
It's juste a carrousel with pictures if the user clicks on a picture I need to display the content in full screen with some navigation (next, previous)
Since I never worked with CORS before, I'm getting a hard time figuring how to pass my data from the iframe to the client website :/
Here's a simplified version of the code
Iframe:
<div class="carrousel">
<div class="carrousel_item">
<img data_id="0">
</div>
<div class="carrousel_item">
<img data_id="1">
</div>
</div>
<script>
var gallery = { 0: url1, 1: url2}
jQuery(document).ready(function(){
jQuery('.carrousel.carrousel_item img').on('click', function(){
var data = { data: gallery, last_iterator: jQuery(this).data('id')}
var event = new CustomEvent('display_post', { detail: data })
return window.parent.document.dispatchEvent(event)
}
})
</script>
ScriptJS:
<script>
window.document.addEventListener('display_post', handleEvent, false)
function handleEvent(e) {
console.log(e.detail)
challenge_marque_explorer = data['data'] // image list
last_iterator = data['last_iterator'] // which image is displayed
display_post_details() // fill an overlay display with the image and nav arrow
}
</script>
If I try it on my domain, everything's is fine
But on an other domain I get error's (this one return : Uncaught DOMException: Permission denied to access property "document" on cross-origin object)
Edit:
After 1 hour making close to no progress, I noticed my FTP soft wasn't succeeding in sending the script, now my code works
Here's my working code using postMessage
iFrame:
var gallery = { 0: url, 1: url}
var origin
window.onmessage = function(event) {
origin = event.origin
};
jQuery(document).ready(function(){
jQuery('.carrousel.carrousel_item img').on('click', function(){
var data = { data: challenge_marque_explorer, last_iterator: i, dest: last_dest, page: 0 }
return window.parent.postMessage(JSON.stringify(data),origin);
}
})
The script for the parent page:
window.onmessage = function(event) {
console.log(event.data)
};
jQuery('#gallery_iframe').load(function(){
document.getElementById('gallery_iframe').contentWindow.postMessage('','*');
})
Thanks guys for your time and help :)
If you're stuck and don't see any progress in one of your script, try using 'alert()' to do a quick check on wether or not your file was really updated
Also think about checking the cache, don't loose time and patience due to a file that wasn't sending
Related
Test page: https://jsfiddle.net/y25rk55w/
On this test page you can see 3 <iframe>'s embeded into each other. Each <iframe> contains a <script> tag in it's <head> tag.
The problem is: only the <script> in the first <iframe> will be loaded by the browser. The other two <script> tags will be present in the dom but the browser will never even try to load them. The problem is not browser specific, it can be reroduced in chrome, firefox, ie. The problem cannot be fixed by adding timeouts or waiting before appending the scripts. It seems to be important that all the iframes have programatically generated content; if you replace this iframes with iframes with actual src links, the problem will disappear.
The question is: how can I actually load a script into iframes 2 and 3?
Full test code:
// It doesn't matter if the scripts exist or not
// Browser won't try to load them either way
var scripts = [
'//testdomain.test/script1.js',
'//testdomain.test/script2.js',
'//testdomain.test/script3.js'
];
function createIFrame(win, onCreated) {
var iframe = win.document.createElement('iframe');
iframe.onload = function () {
onCreated(iframe);
};
win.document.body.appendChild(iframe);
}
function loadScript(win, url) {
var script = win.document.createElement('script');
script.src = url;
script.onload = function() {
console.log("Script " + url + " is loaded.");
};
win.document.getElementsByTagName('head')[0].appendChild(script);
}
createIFrame(window, function(iframe1) {
loadScript(iframe1.contentWindow, scripts[0]);
createIFrame(iframe1.contentWindow, function (iframe2) {
loadScript(iframe2.contentWindow, scripts[1]);
createIFrame(iframe2.contentWindow, function (iframe3) {
loadScript(iframe3.contentWindow, scripts[2]);
});
});
});
Your code is working fine --> http://plnkr.co/edit/vQGsyD7JxZiDlg6EZvK4?p=preview
Make sure you execute createIFrame on window.onload or DOMContentLoaded.
var scripts = [
'https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.js',
'https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.js',
'https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js'
];
function createIFrame(win, onCreated) {
var iframe = win.document.createElement('iframe');
iframe.onload = function () {
onCreated(iframe);
};
win.document.body.appendChild(iframe);
}
function loadScript(win, url) {
var script = win.document.createElement('script');
script.src = url;
script.onload = function() {
console.log("Script " + url + " is loaded.");
};
win.document.getElementsByTagName('head')[0].appendChild(script);
}
window.onload = function(){
createIFrame(window, function(iframe1) {
loadScript(iframe1.contentWindow, scripts[0]);
createIFrame(iframe1.contentWindow, function (iframe2) {
loadScript(iframe2.contentWindow, scripts[1]);
createIFrame(iframe2.contentWindow, function (iframe3) {
loadScript(iframe3.contentWindow, scripts[2]);
});
});
});
};
In the question you can see that I was ommiting the protocol:
/* This is valid to omit the http:/https: protocol.
In that case, browser should automatically append
protocol used by the parent page */
var scripts = [
'//testdomain.test/script1.js',
'//testdomain.test/script2.js',
'//testdomain.test/script3.js'
];
The thing is, programatically created iframes have protocol about: (or javascript:, depending on how you create them). I still can't explain why the first script was loading or why the other two scripts were not showing up in the network tab at all, but I guess it's not very important.
The solution: either explicitly use https:// or programatically append protocol using something like the following code:
function appendSchema(win, url) {
if (url.startsWith('//')) {
var protocol = 'https:';
try {
var wPrev = undefined;
var wCur = win;
while (wPrev != wCur) {
console.log(wCur.location.protocol);
if (wCur.location.protocol.startsWith("http")) {
protocol = wCur.location.protocol;
break;
}
wPrev = wCur;
wCur = wCur.parent;
}
} catch (e) {
/* We cannot get protocol of a cross-site iframe.
* So in case we are inside cross-site iframe, and
* there are no http/https iframes before it,
* we will just use https: */
}
return protocol + url;
}
return url;
}
I've been successful using a simpler method than what the OP proposes in the self-answer. I produce the URLs using:
new URL(scriptURL, window.location.href).toString();
where scriptURL is the URL that needs to be fixed to get a proper protocol and window is the parent of the iframe element that holds the scripts. This can take care of scenarios that differ from the OPs example URLs: like relative URLs (../foo.js) or absolute URLs that don't start with a host (/foo.js). The above code is sufficient in my case.
If I were to replicate the search through the window hierarchy that the OP used, I'd probably do something like the following. This is TypeScript code. Strip out the type annotations to get plain JavaScript.
function url(win: Window, path: string): string {
// We search up the window hierarchy for the first window which uses
// a protocol that starts with "http".
while (true) {
if (win.location.protocol.startsWith("http")) {
// Interpret the path relative to that window's href. So the path
// will acquire the protocol used by the window. And the less we
// specify in `path`, the more it gets from the window. For
// instance, if path is "/foo.js", then the host name will also be
// acquired from the window's location.
return new URL(path, win.location.href).toString();
}
// We searched all the way to the top and found nothing useful.
if (win === win.parent) {
break;
}
win = win.parent;
}
// I've got a big problem on my hands if there's nothing that works.
throw new Error("cannot normalize the URL");
}
I don't have a default return value if the window chain yield nothings useful because that would indicate a much larger issue than the issue of producing URLs. There'd be something wrong elsewhere in my setup.
Objective: Copy a chunk of HTML and send it to a website on another domain.
My problem: The website I'm working on and the website in the iframe are on different domains. I own both of them and have set the Access-Control-Allow-Origin to allow the websites to communicate to each other. However, I can't seem to pass the HTML chunk to the parent window.
I've tried parent.window.postMessage(chunk, http://www.parent-page.com) (chunk is the chunk of HTML code) but I get this error:
Uncaught DataCloneError: Failed to execute 'postMessage' on 'Window': An object could not be cloned.
I have also tried to use ajax to send a PUT request to the parent window but, I get a 404 error that it cannot find the parent window. *I am running the parent window from my local server.
My Question: Can anyone tell me the best way to send an object, containing HTML code, from an iframe to the parent window given that the two websites are NOT on the same domain?
EDIT: I removed the stuff about a skeleton object as that was out of the scope of the question I was really trying to ask.
Here is what I wrote to solve this. Any constructive criticism is welcome.
Code on parent window's website:
//send a message to the website in the iframe
$("#frame").on("load", function (event) {
var viewContainer = $('#element-highlight');
var iframe = document.querySelector('iframe');
var receiver = iframe.contentWindow;
var location = 'http://www.child-website.com';
event.preventDefault();
receiver.postMessage("sendStructure",location);
});
//listen for a response
window.addEventListener('message', function(event) { //event = onmessage event object
if (~event.origin.indexOf('http://ccook.oegllc.com')) { //indexOf returns a -1 if the searchValue is not found
var structure = event.data;
var container = document.getElementById("element-highlight");
container.innerHTML = structure;
}
}
<script src="../jquery/3.0.0/jquery.min.js"></script>
<body>
<div id="frame-container">
<iframe id="frame" src="http://www.main-site.com" frameborder="0"></iframe>
<div id="element-highlight">
<!-- Store Skeleton Copies here -->
</div>
</div>
</body>
Code on the website that is shown in the iframe:
I can't get the case statement below to look any better.
//listen for command from main-site.com
window.addEventListener('message', function(event) { //event = onmessage event object
if (~event.origin.indexOf('http://www.main-site.com')) { //indexOf returns a -1 if the searchValue is not found
switch(event.data){
case "sendStructure":
var structure = getStructure(),
tempNode = document.createElement("div");
structure.appendTo(tempNode); //appends structure to html document
var str = tempNode.innerHTML; //creates a serilized version of the structure
parent.window.postMessage(str, event.origin); //send structure string to main-site.com
break;
//I reccomend using a case statement if the two sites will be sending more than one message to each other
default:
sendError();
}
}
});
function getStructure(){
//this method creates a skeleton of the course page you are on
//returns a skeleton object
console.log("compiling structure");
var viewFrame = $('body').contents(); //<-change 'body' to whatever element you want to copy
var visible = viewFrame.find('*:not(html body)').filter(':visible');
var overlayElements = visible.map(function (i, el) {
var el = $(el);
var overlayEl = $('<div>');
overlayEl.addClass('highlight').css($.extend({
position: 'absolute',
width: el.outerWidth(),
height: el.outerHeight(),
'z-index': el.css('z-index')
}, el.offset()));
return overlayEl.get();
});
return overlayElements;
}
function sendError(){
console.log("main-website's request could not be understood");
}
Well I am unable to lazy load images for some reason. Here is the waterfall view of the tested site
Apparently I am using two lazy load scripts with lazy load script 1 which works but kills the lightbox plugin and also requires lots of tweaking using data-src and src and class="lazy-load" attributes. which I am using for non post related images.
But the main problem lies in the second script which requires Jquery but doesn't require any tweaking with the images. The script is called stalactite (via Github) which I am using like this
<script charset='utf-8' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js' type='text/javascript' />
<script href='http://googledrive.com/host/0B2xMFcMT-eLiV1owdlBMeklGc2M' type='text/javascript' />
<script type='text/javascript'>
$( 'body').stalactite({
loader: '<img/>' // The contents of the loader. Defaults to a dataURL animated gif.
});
</script>
You can find the link of the stalactite script in the above code and here is the documentation.
I don't know why it doesn't work ! Or am I executing it wrongly.
A solution to the problem will be very helpful. Many thanks in advance.
If you are tired of trying to use lazy load libraries and haven't managed to make all of it work, I can suggest you to create lazy load script on your own, or you can take a look at this code below.
By only using jQuery and without needing any other library, you can use this script to achieve the lazy load (I modified the codes from the original one that I used at work):
var doLazyLoad = true;
var lazyLoadCounter = 0;
var lazyLoadMax = 2; // Maximum number of lazy load done
// Button to indicate lazy load is loading,
// or when lazy load has reached its maximum number,
// this button load data manually.
// You can replace this with something like gif loading animation.
var $btnLoadMore = $("#btn-lazy-load-more");
// I use AJAX function to get the data on lazy load
var ajaxFn = function (enableScrollAnim = true) {
var loadingStr = 'Loading...',
idleStr = 'Load more',
ajaxUrl = 'http://www.example.com/posts',
ajaxHeaders = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'},
ajaxData = {
start: $('.posts-wrapper .post').length
};
$btnLoadMore.text(loadingStr); // You can disable the button to prevent manual loading
return $.ajax({
url: ajaxUrl,
type: 'GET',
dataType: 'json',
data: ajaxData,
headers: ajaxHeaders,
// On success AJAX, append newly loaded data to lazy load container.
// Here in my example, the GET request returns data.view i.e. the content, and data.total i.e. total number of posts
success: function (data) {
var $newLoadedPosts = $(data.view),
nlsMarginBottom;
$('.posts-wrapper').append($newLoadedPosts);
$newLoadedPosts.css('display', 'none').fadeIn();
// Animate auto scroll to newly loaded content
if (enableScrollAnim) {
$('html, body').animate({
scrollTop: $newLoadedPosts.first().offset().top
});
}
if ($('.posts-wrapper .post').length < data.total) {
$btnLoadMore.text(idleStr); // If you disable the button, enable the button again here
} else {
// Remove the button when there's no more content to load.
// Determined by data.total
$btnLoadMore.remove();
}
},
error: function () {
$btnLoadMore.text(idleStr); // If you disable the button, enable the button again here
}
});
};
// Do the lazy load here
if ($btnLoadMore.length) {
$(window).scroll(function () {
var scrollOffset = (($btnLoadMore.offset().top - $(window).height()) + $btnLoadMore.height()) + 100;
var hasReachedOffset = $(window).scrollTop() >= scrollOffset;
var isLmsBtnExist = $btnLoadMore.length;
if (hasReachedOffset && lazyLoadCounter < lazyLoadMax && doLazyLoad && isLmsBtnExist) {
doLazyLoad = false;
ajaxFn(false).always(function () {
doLazyLoad = true;
lazyLoadCounter++;
});
}
});
}
$btnLoadMore.click(ajaxFn);
And here is the GIF demo image of my working code.
If you need any further explanation, just comment this answer and I will try to help you.
I am trying to combine ContentFlow (http://jacksasylum.eu/ContentFlow/) and ColorBox (http://www.jacklmoore.com/colorbox/): when the user clicks on an image in ContentFlow I want an HTML page to be displayed in ColorBox.
I have tried using the code provided by the ColorBox examples' section to no avail. The HTML page is loaded by the browser as a normal link (not in ColorBox.)
I have even tried creating a ContentFlow addon (using the LightBox addon as an example) without any luck - nothing is displayed, not even simple images:
onclickActiveItem: function (item) {
var content = item.content;
if (content.getAttribute('src')) {
if (item.content.getAttribute('href')) {
item.element.href = item.content.getAttribute('href');
}
else if (! item.element.getAttribute('href')) {
item.element.href = content.getAttribute('src');
}
if (item.caption)
item.element.setAttribute ('title', item.caption.innerHTML);
colorbox.show(item.element);
}
}
Edited on 01/Oct/2013
The problem only manifests itself when an item contains an href. To prove this I changed the code above to show a static web page:
$.colorbox({open:true, href:"http://mysite.gr/colorbox/content/static.html"});
It the item is just a simple image the static web page is displayed in ColorBox. But if the item contains an href to the web page I want displayed in ColorBox the browser follows the link and loads the specified page. Any ideas on how to stop this from happening?
Thank you in advance for your help!
I have finally solved the problem I have described in my question. The solution involves creating a ContentFlow addon as follows:
new ContentFlowAddOn ('colorbox', {
init: function () {
var colorboxBaseDir = this.scriptpath+"../colorbox/";
var colorboxCSSBaseDir = colorboxBaseDir;
var colorboxImageBaseDir = colorboxBaseDir;
this.addScript(colorboxBaseDir+"jquery.colorbox.js");
this.addStylesheet(colorboxCSSBaseDir+"example3/colorbox.css");
},
ContentFlowConf: {
onclickInactiveItem: function (item) {
this.conf.onclickActiveItem(item);
},
onclickActiveItem: function (item) {
var content = item.content; // ContentFlow's content class
var theItem = item.item; // ContentFlow's item class - if you need access to it
var hrefToDisplay = '';
if (content.getAttribute('src')) {
if (content.getAttribute('href')) {
hrefToDisplay = item.content.getAttribute('href');
}
else if (!item.element.getAttribute('href')) {
hrefToDisplay = content.getAttribute('src');
}
$.colorbox({iframe:true, href:hrefToDisplay, title:item.caption});
}
}
}
});
The secret is to open the HTML page in an iframe.
Hope this helps!
What I am trying to do is load images that I am dynamically generating one after another before page fully loaded. Here is what I am doing. I am making ASYNC requests to server via createXMLHttpRequest. On a server side I am creating new image (chart image) and returning image attributes in JSON format.
Here is snippet of html code:
<!-- first image -->
<div id="image3Obj">
<div id="image3"><img src="img/loader32.gif"></div>
</div>
<!--second image -->
<div id="image2Obj">
<div id="image2"><img src="img/loader32.gif"></div>
</div>
<!-- third image-->
<div id="image1Obj">
<div id="image1"><img src="img/loader32.gif"></div>
</div>
<script type="text/javascript" defer>load_components();</script>
Snippet of Javascript code:
<SCRIPT LANGUAGE="Javascript" src="js_lib/ajaxCaller.js"></SCRIPT>
<script type="text/javascript">
function load_components() {
createUrlStr('url1');
createUrlStr('url2');
createUrlStr('url3');
}
function createUrlStr(url)
// make async request to server and generating brand new image, then returning image div name, source, width and height back in json format
ajaxCaller.getPlainText(url_str, loadImage);
}
function loadImage() {
var jsonObj = eval('(' + xReq.responseText + ')');
if (jsonObj.imgDiv != undefined && jsonObj.imgSrc != undefined) {
var newImg = document.createElement("img");
newImg.src = jsonObj.imgSrc;
if (jsonObj.imgWidth != undefined && jsonObj.imgHeight != undefined) {
newImg.width = jsonObj.imgWidth;
newImg.height = jsonObj.imgHeight;
}
document.getElementById(jsonObj.imgDiv).appendChild(newImg);
}
}
</script>
Problem is that images get loaded one after another on html, but only getting displayed when last image is loaded. Any idea what am I missing here?
My guess, without seeing an actual example, is that because you are running all 3 async requests at the same time it all happens so quickly they appear to happen at the same time when really they may be spaced apart by a few milliseconds. If you delay your requests like the following example does it appear as desired?
function load_components() {
var x,y,z;
x = setTimeout(function(){ createUrlStr('url1'); }, 100);
y = setTimeout(function(){ createUrlStr('url2'); }, 2000);
z = setTimeout(function(){ createUrlStr('url3'); }, 5000);
}
Also keep in mind that while you are generating the image on the server-side and inserting the tag in order, the image data is being downloaded after the fact by the browser not your AJAX request. To see this happening check out the NET tab in Firebug.