change src of iframe and then reload the iframe - javascript

I managed to change an iframe's src with javascript
var path='images/tattoo/fullsize/';
var h=$('#borderlessFrame').height();
var bigFrame=$('#borderlessFrame');
function loadGallery(num)
{
bigFrame=$('#borderlessFrame');
var galPath=path + num; // path to the image
h=$('#borderlessFrame').height();
var source=bigFrame.attr('src');
source='i load some address here';
}
But for now i see the old content of the iframe , is there a way to reload the iframe ( only iframe not the whole page)
The thing i am trying to achieve is a simple gallery , thumb pictures on the bottom and a large picture on the top ( iframe ). On click on any of the thumbs , i change the content of the iframe without reloading the actual page.
Keep in mind that i am new to html/javascript/jquery.
So basically i need a way(function?) to reload the iframe.

To set attribute, you need to call .attr( attributeName, value )
Try this:
var source='i load some address here';
bigFrame.attr('src', source);
Reference:
jQuery .attr()

jQuery has the load method, which is useable like so (assuming borderlessFrame is the id of the <iframe>):
var iFrame = $('#borderlessFrame');
iFrame.load('http://theurltoload.com')
However, iframes seem like an unnecessary approach for your requirements, consider looking into CSS and the jQuery DOM manipulation methods a little more.

Related

Prevent iframe from loading on mobile

I am working on my portfolio page and I want to have my projects in a demo mode where the user can preview the sites in different viewports. I got the idea from here:
http://my.studiopress.com/themes/genesis/#demo-full
On mobile devices I would like to keep the iframes from loading, and instead have links to the projects open the sites in the new tab.
If I have the divs containing the iframes hidden at the very top of my CSS file with display:none, I can see the iframes still load in the background and the page takes a long time to load.
Is there any way to keep them from loading at all when on a certain device or viewport size?
You could achieve this by using JavaScript and the HTML Data-Attribut. By setting the src-Attribute to something like "#" it won't load anything. You can use the data-Attribute to store the URL for use with JavaScript.
<iframe src="#" data-src="https://placekitten.com/200/300" frameborder="0"></iframe>
Then you just check to screen size with window.matchMedia() and set the src-attribute at a specific screen size.
var $iframe = $('iframe'),
src = $iframe.data('src');
if (window.matchMedia("(min-width: 480px)").matches) {
$iframe.attr('src', src);
}
Here is a working example: https://jsfiddle.net/5LnjL3uc/
If you want to show the iframe after a user resizes the window you need to put your code into a function and bind it to a resize event:
var $iframe = $('iframe'),
src = $iframe.data('src');
function showIframe() {
if (window.matchMedia("(min-width: 480px)").matches) {
$iframe.attr('src', src);
}
}
$(window).on('resize', showIframe);
// Initialize it once on document ready
showIframe();
Working Example: https://jsfiddle.net/5LnjL3uc/1/
A better solution is to approach this in reverse.
IE do not load the src to begin with by placing your URL in a attribute like 'data-src' for example.
See my code for this below. You simply copy the data-src to your src when your device, or device width is not mobile/mobile size.
I believe this is the best solution because there are no uncertainties. With the previously mentioned solutions (which I tried) you are racing against the clock with the browser for when your code runs and it decides to load the iframe src.
if(device !== true) {
// add '#' to the href
let iframe = document.getElementById('3dExperience')
iframe.src = iframe.getAttribute('data-src')
}
Note: 'device' is the is-mobile npm package for detecting mobile.

How can I resize the iframe without page refresh?

I have some swf embedded in iframe but only if the page is refreshed the iframe is resized, then if I select other one then will show as all swf not only the animation the background as well. This is what I am using
if ( 'resizeIframe' === $('#onPlayAction').val() ) {
var ifrEl = $('div.player-container iframe.page-iframe')[0];
$(ifrEl).show();
ifrEl.src = htmlPageBrowserUri;
ifrEl.onload = function() {
ifrEl.width = ifrEl.contentWindow.document.body.scrollWidth;
ifrEl.height = ifrEl.contentWindow.document.body.scrollHeight;
}
}
There are three ways to do this.
You can change the size on every window resize
$(window).on('resize', function (){
ifrEl.width = ... ;
ifrEl.height = ... ;
})
You can use some jQuery plugins like iFrame Resizer
You can use some nifty css tricks. Go search for responsive iframes using css and you will find a ton of good answers.
I hope this all helps you.
I suspect the issue with your code might be thses two lines :
ifrEl.src = htmlPageBrowserUri;
ifrEl.onload = function() {
The problem being that the first line set s the frame address, but second line sets the onload event immediately, probably before the page has loaded ? So when the page does load, the line setting onload event has already run & so doens't get set.
I don't quite understand the text in your question (sorry!) but the code below successfully resizes an iframe - it's run 'onload' in the frame's page:
<body onload="setParent()">
In case it's relevant, the iframe itself has attributes:
<iframe id="neckfinishframe" style="width:100%;overflow-x:hidden" src=".. etc">
In my case I'm only concerned about height. Width is 100%.
In the iFrame page, this code runs from the onload event to amend the iframe height to be whatever the height of the page is, plus a bit. This is intended to avoid showing a set of scroll bars within the iframe.
function setParent() {
// runs onload in iframe page
// in my case I have to run it from the frame page because I need to know the page rendered height in order to set the iframe height
var f;
try {f = parent.getElementById("neckfinishframe")} catch (e) {};
if (f != null) f.style.height=(this.document.body.scrollHeight+30)+"px";
}
Note - I haven't tried this cross- browser but I know it works in IE.

Once an image has failed loading, how can I make the browser retry?

I'm making a Chrome extension which in order to reduce bandwidth usage it stops all outcoming requests which are images.
I want to provide functionality where if the user clicks on the image (or technically a layer on top of that image) it would try to reload the image, this time not being blocked by the extension.
How can I tell the browser to retry loading the image? And if there isn't a straightforward way to do it, what would be a work around? Deleting the old image from the DOM and adding it again?
Any help is appreciated. :)
EDIT 1:
To answer #CBroe's question:
Using the chrome.webRequest.onBeforeRequest API in a background script.
To answer #jfriend00's question:
The usual placeholder "couldn't load image" icon, I guess also known as "broken file" icon:
See all those broken images?
That screenshot also illustrates the point of a layer on top of another image. Should those images not be broken, the loaded image would be there but that layer (the one in a dark grey which shows the image's dimensions) still remains there.
The desired href still exists there in the img tag:
If simply assigning the same src value to the img element is not enough¹, then create a new Image object in JavaScript, and assign the value to its src property.
¹ It might not be, if the browser just goes, “oh hey, that is the same value for the src attribute that the img already had, so I don’t have to do anything” – creating a new JS Image object however should make the browser request that resource again if he realizes he does not have it cached already.
What I would do instead is replace the URLs of the images with an image from your extension. A 1x1 pixel transparent GIF or PNG.
When you do this, add an attribute to all of the elements you replaced... something like data-yourextension-originalurl, with the URL of the original image. If the user then wants to load images, it's easy enough to go back and fix those image elements.
While I'm not too familiar with the Chrome API, a quick glance seems to suggest that there's no way to get the specific img element from each onBeforeRequest, which you'd need to know in order to figure out where to attach custom code.
This may be better accomplished with native JavaScript of some sort. For example, if Chrome lets you inject code on load, you could apply a function like the one below to all img elements after document load but before image load.
// Given an img element, replaces its src with a placeholder URL,
// and sets its click action to load its original src
function makePlaceholder(elem){
elem["data-oldtitle"] = elem.title;
elem["data-oldhref"] = elem.href;
elem["data-oldsrc"] = elem.src;
elem["data-oldonclick"] = elem.onClick;
elem.title = "Click to load the blocked image.";
elem.href = '';
elem.src = "http://example.com/placeholder.png";
elem.onClick = function(){
this.src = this["data-oldsrc"];
this.title = this["data-oldtitle"];
this.href = this["data-oldhref"];
this.onClick = this["data-oldonclick"];
};
}
The simple way to force reloading an image in JavaScript is:
var img = document.getElementById("myImage");
img.src = img.src.replace(/\?.+/,"") + "?" + new Date().getTime();
This adds a unique QueryString to the image which basically forces the browser to not use a cached version of the image.

javascript to cancel image loading

I am looking for a way to cancel image loading using javascript. I've looked at other questions and hiding them is not enough. Also, the rest of the page must load (window.stop() is out of the question).
The page that is being loaded is not under my control, only one thing is guaranteed - the first <script> on the page is my javascript (lightweight - no jquery).
I have tried setting all img sources to nothing, that did not help since the dom is created after the page is parsed, and all browsers have the same behavior - the img is loaded once it is parsed.
Not possible with modern browsers. Even if you alter the src attribute of image tag with JavaScript browsers still insist on loading the images. I know this from developing the Lazy Load plugin.
The only way I can see to stop images loading is to not have an src attribute present in the image itself, and using a custom data-* attribute to hold the location of the image:
<img data-src="http://path.to/image.png" />
Obviously this doesn't gracefully degrade for those (admittedly rare) JavaScript disabled browsers, and therefore requires a noscript fall-back:
<img data-src="http://path.to/image.png" />
<noscript><img src="http://path.to/image.png" /></noscript>
And couple this with a simple function to load the images when you, or your users, are ready for them:
/* simple demo */
function imagePopulate(within, attr) {
within = within && within.nodeType == 1 ? within : document;
attr = attr || 'data-src';
var images = within.getElementsByTagName('img');
for (var i = 0, len = images.length; i < len; i++) {
if (images[i].parentNode.tagName.toLowerCase() !== 'noscript') {
images[i].src = images[i].getAttribute(attr);
}
}
}
document.getElementById('addImages').onclick = function(){
imagePopulate();
};
JS Fiddle demo.
I can't be sure for all browsers, but this seems to work in Chrome (in that there's no attempt, from looking at the network tab of the developer tools, to load the noscript-contained img).
It can be done with webworkers. See the following example:
https://github.com/NathanWalker/ng2-image-lazy-load.
Stopping a web worker cancels the image loading in browser
Recalling the onload event:
window.onload=function(){
imgs = document.getElementsByTagName('img');
for(i = 0; i < imgs.length(); i++){
imgs[i].src = '#';
}
};
If you want to only cancel the loading of the image , you can use sємsєм's solution
but i do not think it will work by using an window onload event .
You will probably need to provide a button to cancel the image load. Also i suggest, instead of setting the src attribute to "#" , you can remove the src attribute itself using
removeAttribute()
[Make sure you disable the cache while testing]
You need a proxy.
Your script can redirect to another server using something like
location.replace('http://yourserver.com/rewrite/php?url='+escape(this.href));
perhaps you tell us why you want to cancel image loading and whose site you are loading on so we can come up with a better solution
If there is nothing on the page other than images, you could try
document.write('<base href="http://yourserver.com/" />');
which will mess with all non-absolute src and hrefs on the page.
UPDATE Horrible hack but perhaps this almost pseudo code (I am off to bed) will do someting
document.write('<script src="jquery.js"></script><div id="myDiv"></div><!-'+'-');
$(function() {
$.get(location.href,function(data) {
$("#myDiv").html(data.replace(/src=/g,'xsrc='));
});
})
The closest you can get to what you maybe want is to have a quickly loaded placeholder image (ie. low resolution version of your image) and a hidden image (eg. {display:none}) in which the large image gets loaded but not displayed. Then in the onload event for the large image swap the images over (eg. display:block for the large image display:none for the smaller). I also use an array (with their url), to reuse any images that have already been opened.
BTW if you open an image in a new webpage when it gets closed then the image loading will be cancelled. So maybe you can do something similar in a webpage using an iframe to display the image.
To close the iframe and therefore unload the image, remove the frame from the DOM
(another advantage is that browsers spawn another process to deal with iframes, so the page won't lock up while the image loads)

How Can I Apply CSS to an iFrame Using OK_loadit Function?

I am attempting to apply CSS to a document that I'm loading into an iFrame. I am using the OK_loadit function as follows:
function OK_loadit(url,layerObjNS, width) {
if (document.layers){
document.layers[layerObjNS].load(url, width);
} else{
if (window.frames.length > -1){
window.frames[layerObjNS].location.href = url;
}
The document I am loading into the iFrame is a php Seresnipity blog page.
The blog page's CSS needs to be set to "background= #000000", so that it can be viewed from links in the RSS feed with a black background. That's already done.
But when the blog page is rendered in it's iFrame on my website (which is located on the same domain as the blog), it's CSS needs to be set to "background= transparent".
Is there any way to modify the OK_loadit script above in such a way that I can reset the background parameter of the page accordingly when it's loaded into the iFrame, or do I need to use a different script altogether?
Either way, I'd really appreciate it if someone here could hook me up with what I need.
Thanks!
James
[edit]
deleted previous answer
[/edit]
sorry, I re-read your question and realized that the solution is easier than I had thought.
in the url that you're passing to this page just add ?tran to the url string..
so...
"myPage.php?tran"
then in the php page add this...
<script>
document.onload = function(){
if(self.location.query.indexOf("?tran") == 0)
document.bgColor = "transparent"
}
</script>
I think that should work.

Categories

Resources