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?
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
http://api.fatherstorm.com/test/4159620.php
using jQuery for this...
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):
Alternatively with
innerHTML
to an element on the page with a predefined name:Or with DOM to insert just before the current
<script>
(though again that can be unpredictable if deferred):Or to insert just before the current 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.
To generate a Tag with jQuery you can use
$('<tagname />')
and pass an object with parameters (for examplesrc
). Afterwards you append this iframe to the Dom. Usinghtml()
you can set the html-content of a selected element (in this case a tag with idexample
) to your iframe.