How to display iframe by a Javascript snippet? - javascript

I have seen some widgets online that gives the user the possibility of including a short Javascript snippet in their own page, which when executed displays an Iframe, like in the following example.
<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=APP_ID&xfbml=1"></script><fb:facepile></fb:facepile>
How can I do this by myself - have a javascript on my server, that when called on a remote server, writes out an iframe or loads content into their page?

The traditional way (considered a bit messy; won't work with XHTML-as-XML host pages; if called after page load via async, will blow up the entire page):
document.write('<iframe src="http://www.example.com/myframe" width="100" height="100"></iframe>');
Alternatively with innerHTML to an element on the page with a predefined name:
document.getElementById('examplecomframe').innerHTML= '<iframe src="http://www.example.com/myframe" width="100" height="100"></iframe>';
Or with DOM to insert just before the current <script> (though again that can be unpredictable if deferred):
(function() {
var iframe= document.createElement('iframe');
iframe.src= 'http://www.example.com/myframe';
iframe.width=iframe.height= 100;
document.getElementById('examplecomframe').appendChild(iframe);
})();
Or to insert just before the current script:
var scripts= document.getElementsByTagName('script');
var script= scripts[scripts.length-1];
script.parentNode.insertBefore(iframe, script);
I wouldn't use jQuery for third-party script inclusion. You'd have to load the whole heavy framework into the enclosing page, just for the sake of a few lines of JS. This can cause clashes with other frameworks (or different versions of jQuery) being used by the host page, something very rude for a third-party script to do.

I think you may have how this is working a bit mixed up. The way it's working is this:
1. User requests page from your domain/server, page is served.
2. Client web browser on users machine interprets said page, if a script block includes a reference to a js file at some other location then said js file is fetched.
3. Javascript is processed by the clients browser.
So really all you need is a JS file (plain old ASCII) on the server and have it do some document.write() calls to add the code you want it to add, for example:
go to http://www.shaunhusain.com/TestIFrameViaJS
three files there involved
index.html
anotherpage.html
testIFrame.js
let me know if it doesn't work out or I took a wrong direction for what you're looking for?
Shaun

To generate a Tag with jQuery you can use $('<tagname />') and pass an object with parameters (for example src).
Afterwards you append this iframe to the Dom. Using html() you can set the html-content of a selected element (in this case a tag with id example) to your iframe.
$(function() {
var iframe = $('<iframe />', {
src: 'http://example.com',
width: 100,
height: 100
});
$('#example').html(iframe);
});

http://api.fatherstorm.com/test/4159620.php
using jQuery for this...
$(document).ready(function() {
$('#fb-root').append('<iframe/>');
$('#fb-root iframe')
.attr('id','my_iframe')
.attr('src','http://www.cnn.com')
.css('width','100%')
.css('height','100%')
.attr('frameborder','no');
});

Related

Using javascript to update <embed> parameter

I've been recently trying to implement a flash application, which at some point needs to be embedded via html. It looks something like>
<embed src=".." quality=".." ... and at some point FlashVars="&firstparam&secondparam..."
What I am trying to do is implement a dropdown, which would when pressed change that FlashVars parameter so the app shows something different. I've tried with
document.getoElementByID().FlashVars="new parameters"
but it doesn't work (it works perfectly for highlited default parameters such as src, height, width...)
I've also tried to write whole embed part again with javascript snippet, but it also didn't work. How is this done in javascript? I'm a beginner in this field so any help is greatly appreciated.
Thanks.
To understand why your code didn't work, you should understand what's flashvars parameter and how it's working.
Adobe said about that here, for example :
The FlashVars parameter of the HTML <OBJECT> tag sends variables into the top level of a SWF file when it loads in a web browser. The <OBJECT> tag is used to add SWF files to HTML pages. The <EMBED> tag can also be used, but is older and now obsolete.
So here we can understand that those variables are loaded when the SWF is loaded and that's why even if you've changed the flashvars parameter, that will do nothing, absolutely nothing to that loaded SWF which should be loaded again to get them (variables) applied.
So to do that, take this simple example :
HTML :
<div id='swf_container'>
<embed id='swf_object' src='swf.swf' flashvars='id=1' />
</div>
JavaScript :
// change the flashvars attribute
var swf_object = document.getElementById('swf_object');
swf_object.setAttribute('flashvars', 'id=2');
var swf_container = document.getElementById('swf_container');
var inner_html = swf_container.innerHTML;
// reload the swf object
swf_container.innerHTML = '';
swf_container.innerHTML = inner_html;
This manner is, of course, working but maybe it's not a good idea to reload the SWF object everytime we need it to do something, and that's why we have ExternalInterface to communicate between the SWF and JavaScript.
So in the case where you've access to the ActionScript code to create that SWF, you can use ExternalInterface to call any function in your SWF when it's already loaded.
For that, take this example :
ActionScript :
if(ExternalInterface.available)
{
// registers an AS function to be called from JS
ExternalInterface.addCallback('from_JS_to_AS', from_JS);
}
function from_JS(id:int) : void
{
// use the id sent by JS
}
JavaScript :
var swf_object = document.getElementById('swf_object');
swf_object.from_JS_to_AS(1234);
... and don't forget to use swfobject to avoid some browsers compatibility and to be sure that you establish the communication between your ActionScript side and the JavaScript one ...
Hope that can help.
Just do this :
$('embed') // targets the embed tag in the DOM
.attr("attribute-name","attribute-value");
Here's an example : https://jsfiddle.net/DinoMyte/1a6mwb13/2/

Write a js script in a div

I am trying to get a script from another website using jQuery then document.write it
here is my code
var url = "https://code.jquery.com/jquery-1.10.2.js";
var dam = $.getScript(url);
document.write(dam);
But this doesn't work!!
all what I get on the page is [object Object]
Can this be achieved without XHR?
jsfiddle
Don't use document.write, it does not do what you think it does. What it does not do is write some data at the end of the document. What it does instead, is pipe data into the current write stream. And if there is no write stream, it will make a new one, resetting the document's content. So calling document.write(dam) means you just wiped your document. document.write is a low level JS function from an earlier era of JavaScript, don't use it.
Instead, you want to use modern DOM manipulation functions, so in jQuery, that's stuff like:
$(document.head).append($("<script>").attr("src", url));
where
$("<script>")
builds a new script element,
$(...).attr("src", url)
sets the "src" attribute to what you need it to be, and:
$(document.head).append(...)
or
$(document.body).append(...)
to get the script loaded into your document. If it's a plain script with src attribute, it can basically go anywhere, and if it's a script with text content that should run, you can only make that happen through document.head.
Although if it's just a script you need to load in and run, you can use getScript, but then you don't need to do anything else, it's just:
var url = "https://code.jquery.com/jquery-1.10.2.js";
jQuery.getScript(url);
Done, jQuery will load the script and execute it. Nothing gets returned.
Of course, the code you're showing is loading jQuery, using jQuery, so that's kind of super-odd. If you just want to load jQuery on your page, obviously you just use HTML:
<!doctype html>
<html>
<head>
...
</head>
<body>
...
<script src="http://https://code.jquery.com/jquery-1.10.2.js"></script>
</body>
</html>
with the script load at the end so the script load doesn't block your page. And then finally: why on earth are we loading jQuery version 1.x instead of 2.x? (if you need to support IE8: that's not even supported by Microsoft anymore, so you probably don't need to).
And finally, if we don't want to load the script, but we really just want its content, as plain text, there's only a million answers on Stackoverflow already that tell you how to do that. With jQuery, that's:
$.get("http://https://code.jquery.com/jquery-1.10.2.js", function(data) {
$(document.body).append($("div").text(data));
});
But you knew that already because that's been asked countless times on Stackoverflow and you remembered to search the site as per the how to ask instructions before asking your question, right?
executing the script on the page is not my goal!. I want to get the
script content and put it a div (USING JAVASCRIPT - NO XHR) , is that
possible ?
Try utilizing an <iframe> element
<div>
<iframe width="500" height="250" src="https://code.jquery.com/jquery-1.10.2.js">
</iframe>
</div>
jsfiddle http://jsfiddle.net/snygv469/3/
Make it easier... use my fiddle
http://jsfiddle.net/wwwfzya7/1/
I used javascript to create an HTML element
var url = "https://code.jquery.com/jquery-1.10.2.js";
var script = document.createElement("SCRIPT"); //creates: <script></script>
script.src = url; //creates: <script src="long_jquery_url.js"></script>
document.body.appendChild(script); //adds the javascript-object/html-element to the page.!!!
Use this way, it can fix your problems.
$.get( "https://code.jquery.com/jquery-1.10.2.js", function( data ) {
alert(data);
});
You can try adding
<script src="http://code.jquery.com/jquery-1.8.3.min.js" ></script>
Then an AJAX call, but it pulls data from CACHE. It looks like an AJAX but when <script> is added file goes in cache, then read from cache in the ajax. In cases where it is not stored in cache read it using normal AJAX.
jQuery.cachedScript = function(url, options) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "text",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
$(document).on('ready', function() {
// Usage
$.cachedScript("http://code.jquery.com/jquery-1.8.3.min.js").done(function(script, textStatus) {
console.log(script);
});
});
Normal Solution
If you are ready to use AJAX look at this fiddle
How to fetch content of remote file and paste it on your document and execute that js code
I guess you want to get content written on remote file and want to write that content in your HTML. to do this you can use load() function.
To do this follow the following steps:
1. Create a file index.html Write the following code in it:
<pre id="remote_script"></pre>
<script>
$(document).ready(function() {
//var url = "https://code.jquery.com/jquery-1.10.2.js";
var url = "remote_script.html";/* For testing*/
$('#remote_script').load(url,function(){
eval($('#remote_script').text()); /* to execute the code pasted in #remote_script*/
});
});
</script>
2. Create another file remote_script.html for testing write alert('a'); in it without any <script> tag and run the above code.

Use a JavaScript variable inside src of script tag

Google provides its script embed code to display a trends Map by placing this code in our site.
<script type="text/javascript" src="//www.google.com.pk/trends/embed.js?hl=en-US&q=iphone&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330"></script>
The above code displays the trends map.
Notice the q=iphone in the above URL. I want to pass a JavaScript variable value instead of hard coding a fixed value like iPhone in this case.
How can I use a JavaScript variable inside the src of script tag?
I tried creating script programmatically, it injects the script code but the script does not get executed.
My try
document.body.appendChild(document.createElement('script')).src= varHavingScriptURL;
My try is in a JS Fiddle here.
The problem is, you can not do this after page load. Look at the source of the script
document.write('<iframe width="500" ... </iframe>');
So you need to do this as the page is rendering because of the document.write.
Now looking at what you did
document.body.appendChild(document.createElement('script')).src = varHavingScriptURL;
That is not going to work, you need to break it up
var scr = document.createElement('script');
scr.src = varHavingScriptURL;
document.getElementsByTagName("head")[0].appendChild(scr);
but again, it is not going to work because of the document.write.
Finally after hours of struggle, I found the solution using PostScribe.
// jQuery used as an example of delaying until load.
$(function
() {
// Build url params and make the ad call
var str= "magic";
postscribe('#ad', '<script src=//www.google.com.pk/trends/embed.js?hl=en-US&q='+str+'&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330><\/script>');
});
Postscribe
Working Demo

how to check if a same domain, dynamically loaded iframe which i have no control over is 100% loaded?

Photo sets in Tumblr are served up as iFrames.
I want to manipulate that iframe via jQuery to look the way i want it too, which I'm able to do, but it doesn't always finish what it's doing.
I think it's because there is a lot of things happening concurrently as the page loads. I need a way to check that this iFrame, which I have no control over, loads 100% before i do the fun stuff.
There are various techniques suggested in other questions about this, but I don't think they are right for this situation. Here's one example from the Stack Overflow question "jQuery .ready in a dynamically inserted iframe"
function callIframe(url, callback) {
$(document.body).append('<IFRAME id="myId" ...>');
$('iframe#myId').attr('src', url);
$('iframe#myId').load(function()
{
callback(this);
});
}
But that makes no sense to me whatsoever to me, even though it got ticked and had 100 upvotes.
In this 'answer' the iframe is being appended by the function. That to me is not a dynamically loaded iframe!
Here is my code with the 'dumb' iframe load checker. The code works, but only sometimes. You can see it in action here http://syndex.me (third post is a photoset)
$(".post_relative").each(function () {
var post_relative = $(this);
var photoset = post_relative.find('.html_photoset');
if(photoset.length){
var myFrame = photoset.find("iframe");
myFrame.load(function(){
var newCover=myFrame.contents().find('.photoset').children(':first-child').children(':first-child').attr("href")+ '?'+(Math.random()*10000);
post_relative.append("<img src='"+ newCover +"' alt='Cover Page' />");
var psHeight = post_relative.find('img');
psHeight.load(function(){
if (psHeight.height()>heightRef){
psHeight.height(heightRef);
}
myFrame.hide();
})
})
}
});
So the question is: How do you execute a script based on the 100% loading and readiness of an iframe?
You have write data outside the context of each frame using the onload event. You have two options:
cookies
localStorage
The second is a vastly superior solution, but it is not supported on IE7. If it is in the same schema, domain, and port then you can access these items from both frames.
If your using jquery have you tried
$("#iFrameId").load(function (){
// do something once the iframe is loaded
});

How do I add an external js file with a parameter

I want to give a minimal js code to random websites so that they can add a widget.
The code needs to run after the main page loads and include a parameter with the domain name. ( I don't want to hardcode it)
One option is to add this code just before the </body> (so It will run after the page loads):
<script type="text/javascript" id="widget_script">
document.getElementById('widget_script').src=location.protocol.toLowerCase()+"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
</script>
This works in IE but not in Firefox. I see with Firebug that the src property is created correctly but the script from my site is not loaded.
My question is : what is the best way to do that ? (preferably by putting minimal lines on the header part.)
To further clarify the question: If I put a script on the header part, how do I make it run after it is loaded and the main page is loaded? If I use onload event in my script I may miss it because it may load after the onload event was fired.
You can try to statically include the script with document.write (is an older technique and not recommended to use as it can cause problems with more modern libraries):
var url = location.protocol.toLowerCase() +
"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
document.write('<script src="', url, '" type="text/javascript"><\/script>');
Or with dynamically created DOM element:
var dynamicInclude = document.createElement("script");
dynamicInclude.src = url;
dynamicInclude.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(dynamicInclude);
Later edit:
To ensure the script is run after onload this can be used:
var oldWindowOnload = window.onload;
window.onload = function() {
oldWindowOnload();
var url = location.protocol.toLowerCase() +
"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
var dynamicInclude = document.createElement("script");
dynamicInclude.src = url;
dynamicInclude.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(dynamicInclude);
}
I do not believe it can be shorter than this, apart from shorter variable names :)
Why not use the getScript method of jQuery to do the loading? If you don't want to be dependant on jQuery, you can trace through the source to learn how they tackled it.
Viewing a widely used library is always going to show you solutions to problems you didn't know you had. For example, you can see how jQuery manages to generate a callback when the script is loaded, and how it avoids a purported memory leak in IE.
You probably want to be implementing the non-blocking script technique. Essentially instead of modifying the src of a script, you're going to create and append a whole new script element.
Good write up here and there are standard ways to do this in YUI and jQuery. It's quite straightforward with only one gotcha which is well understood (and documented at that link).
Oh and this:
One option is to add this code just
before the </body> (so It will run
after the page loads):
...is not technically true: you're just making your script the last thing in the loading order.

Categories

Resources