is it possible change or append hyperlink in a iframe?
Here is my code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function changelinks(iframe){
var as = iframe.contentDocument.getElementsByTagName('a');
for(i=0;i<as.length;i++){
as[i].setAttribute('href',"http://www.yahoo.com");
}
}
</script>
</head>
<body>
<iframe src="http://www.google.com" onload="changelinks(this)"></iframe>
My goal is when click on any link under iframe, destination url will be www.yahoo.com.
any suggestion is welcome.
UPDATE I fetch website in iframe not located in my server.
Since you are using jquery.
function changelinks(iframe) {
var frame = $( iframe ).get(0).contentDocument;
$( 'a', frame ).click(function( event ) {
event.preventDefault();
location.href = 'http://yahoo.com';
});
}
Or changing element attribute:
function changelinks(iframe) {
var frame = $( iframe ).get(0).contentDocument;
$( 'a', frame ).each(function() {
$(this).attr('href', 'http://yahoo.com');
});
}
If the iframe url is an external url you run into an injection security issue...
see this: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
this means you can only access DOM on your domain sites.
you can do some php "proxy" hacks, where you can change the href attr but with simple javascirpt its not working.
(btw: there are some greasemonkey ways, but i think this is not an option for your site :))
regards
Thomas
Related
Info: I was working on it for so long, I have a webpage that contains an iframe. Inside that iframe i have opened a page (application) from my own site.
Question: I'm trying to get the <div class = "ps-lightbox"> </ div> inside that iframe out of the iframe. but i cant figure it out with jQuery..
I know it sounds confusing. But I hope you understand my explanation.
Does anyone know how to fix this? You could save my day..
Screenshot of the webpage <
You can not access the elements which are not part of iframe document. But if you have iframe of your own website then window.postMessage can do the trick.
Consider below example:
mainPage.html
<html>
<head>
<script type="text/javascript">
window.addEventListener("message", function(evnet){
if(event.type === "GET_SOME_ELEMENT"){
var iframeWindow = document.getElementsById("iframe1")[0].contentWindow;
iframeWindow.postMessage("POST_SOME_ELEMENT", "TARGET_ORIGIN", {element: $(".some-element")}
}
});
<script/>
</head>
<body>
<div class="some-element"/>
<iframe id="iframe1" src="iframePage.html"/>
</body>
</html>
iframePage.html
<html>
<head>
<script type="text/javascript">
if(window.parent){
window.parent.postMessage("GET_SOME_ELEMENT", "TARGET_ORIGIN");
window.addEventListener("message", function(evnet){
if(event.type === "POST_SOME_ELEMENT"){
console.log(event.data.element);
}
});
}
<script/>
</head>
</html>
The exact question is how to do it with pure JavaScript, not with jQuery.
But I always use the solution that can be found in jQuery's source code. It's just one line of native JavaScript.
For me, it's the best, easily readable and even afaik the shortest way to get the content of the iframe.
First get your iframe
var iframe = document.getElementById('id_description_iframe');
// or
var iframe = document.querySelector('#id_description_iframe');
And then use jQuery's solution
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
It works even in the Internet Explorer which does this trick during
the contentWindow property of the iframe object. Most other browsers
use the contentDocument property and that is the reason why we proof
this property first in this OR condition. If it is not set to try
contentWindow.document.
Select elements in iframe
Then you can usually use getElementById() or even querySelectorAll() to select the DOM-Element from the iframeDocument:
if (!iframeDocument) {
throw "iframe couldn't be found in DOM.";
}
var iframeContent = iframeDocument.getElementById('frameBody');
// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');
Call functions in the iframe
Get just the window element from iframe to call some global functions, variables or whole libraries (e.g. jQuery):
var iframeWindow = iframe.contentWindow;
// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');
// or
iframeContent = iframeWindow.$('#frameBody');
// or even use any other global variable
iframeWindow.myVar = window.myVar;
// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);
Note
All this is possible if you observe the same-origin policy.
This might help you
var html = $(".ps-lightbox").contents().find("body").html()
And btw, you can get access to iframe's content only from the same origin due to XSS protection
Make sure your code is inside jQuery ready event.
// This won't work
$("#iframe").contents().find('.ps-lightbox');
// This will work
$(function() {
$("#iframe").contents().find('.ps-lightbox');
})
this is my part of code now i'm using iframe tag and loaded epub on iframe tag
then i don't know how to get all elements inside iframe tag.
jQuery(document).ready(function($) {
var tmp = $('#epub_loader iframe').contents().find('body').html();
alert(tmp);
});
<iframe id="epub_loader" href="test.epub" ></iframe>
`
Assuming both your frames are on the same domain and there is no restriction with Same Domain Policy, you can use the following code from the "parent" frame to get an element in the "child" iframe (in your case body tag).
Pseudo code, you need to actually point to your iframe DOM by id:
var html = document.getElementById('iframe').contentDocument.body.innerHTML;
Notes: In case iframe is on a different domain, you have limited access for browser security reasons.
The thing you need is to wait document will be fully loaded coz you are used iframe,then you should call ....
jQuery(document).ready(function() {
window.onload = function () { //call when iframe is fully loaded
var tmp = $('#epub_loader').contents().find('body').html();
alert(tmp);
};
});
I am trying to load a popup lightbox window when the page is initially opened. I can get it to work on a click but I cannot get the code right to add a class in the script. I am using 'Lightbox' from within HTML Kickstart.
The link that works looks like this: <a class="lightbox" href="#bbc">BBC</a> This works perfectly. Basically how do I get that to work automatically on page load.
My attempt at the script:
<script type="text/javascript">
function load() {
var target = location.href = "#bbc";
target.className = "lightbox";
}
</script>
So I assume you want to add a class to that anchor tag:
$(function () {
$("a[href=#bbc]").addClass("lightbox");
});
Using $(function() {…}) is the same as using the ready() function (in JQuery). I would recommend running the code after the DOM is ready rather the "on load".
you need to call the load() function on the onLoad event of <body> tag.
<body onLoad="load()">
The way I read this question — ignoring the title — is that the user is trying to trigger the lightbox on load. Whilst this may be a wrong assumption, the way to trigger a link using javascript is to use the .click() method:
window.onload = function(){
var i, list = document.getElementsByTagName('a');
for ( i=0; i<list.length; i++ ) {
/// this will only work for links with only a class name of lightbox.
/// you could look into using getElementsByClassName or something similar.
/// I use getElementsByTagName because I know how supported it is.
if ( list[i].className == 'lightbox' ) {
list[i].click();
}
}
};
The above code would support multiple lightbox links in a page, which might not be desired, so it may be best just to add an id to the link you wish to target and then use:
window.onload = function(){
document.getElementById('clickonload').click();
};
<a id="clickonload" class="lightbox" href="#bbc">BBC</a>
You may find however, that in reading the documentation for whatever lightbox plugin you are using, that there is a command you can use from JavaScript, rather than clicking a target link.
$(window).load(function () {
var target = location.href = "#bbc";
target.className = "lightbox";
});
I am trying to do something similar to the Clipper application here http://www.polyvore.com/cgi/clipper
I can make the iframe appear in another website (cross domain). But I cannot make the "close" button to work.
This is what I used but it doesn't work for cross domain (basically remove the iframe element)
window.parent.document.getElementById('someId').parentNode.removeChild(window.parent.document.getElementById('someId'));
Can you help? Thanks.
You should use a library that abstracts this (e.g. http://easyxdm.net/wp/ , not tested). Fragment ID messaging may not work in all browsers, and there are better approaches, such as postMessage.
However, your example (Clipper) is using a hack called fragment id messaging. This can be cross-browser, provided the page containing your iframe is the top level. In other words, there are a total of two levels. Basically, the child sets the fragment of the parent, and the parent watches for this.
This is a similar approach to Clipper's:
parent.html
<html>
<head>
<script type="text/javascript">
function checkForClose()
{
if(window.location.hash == "#close_child")
{
var someIframe = document.getElementById("someId");
someIframe.parentNode.removeChild(someIframe);
}
else
{
setTimeout(checkForClose, 1000)
}
}
setTimeout(checkForClose, 1000);
</script>
</head>
<body>
<iframe name="someId" id="someId" src="child.html" height="800" width="600">foo</iframe>
</body>
</html>
child.html:
<html>
<head>
<script type="text/javascript">
setTimeout(function(){window.parent.location.hash = "close_child";}, 5000);
</script>
<body style="background-color: blue"></body>
</html>
EDIT2: Cross-domain and independently controlled are different. I dug into the (heavily minified/obfuscated) Polyvore code to see how it works (incidentally, it doesn't in Firefox). First remember that bookmarklets, such as the Clipper, live in the context of the page open when they start. In this case, the bookmarklet loads a script , which in turn runs an init function which generates an iframe, but also runs:
Event.addListener(Event.XFRAME, "done", cancel);
If you digg into addListener, you'll find (beautified):
if (_1ce2 == Event.XFRAME) {
if (!_1cb3) {
_1cb3 = new Monitor(function () {
return window.location.hash;
},
100);
Event.addListener(_1cb3, "change", onHashChange);
}
}
cancel includes:
removeNode(iframe);
Now, the only remaining piece is that the iframe page loads another script with a ClipperForm.init function that includes:
Event.addListener($("close"), "click", function () {
Event.postMessage(window.parent, _228d, "done");
});
So we see clearly they are using fragment ID messaging.
Try hiding the contents of the iframe, and don't worry about actually getting rid of the iframe element in the parent.
There is another implementation of the old hash hack. It's backwards compatible, easy javascript-only, and very easy to implement:
http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/
I'm currently using an IFrame to sandbox user generated content on a website. This eliminates any styling issues with our main stylesheets.
However, when a user generates a link using our rich text editor, we would like the link to open in the parent and not just open the link in the IFrame. I realize you can set a target to the parent, but we do not have control of the user and what they enter in their content.
Is there any way to hijack the HREFs inside the IFrame so they all target parent without modifying them? Or use a bit of Javascript that could be injected universally so I do not need to scrape through all of the content and replace the target programatically?
Ideally a simple script in one spot would be the best solution.
Thoughts?
END SOLUTION
I used a variation of the answer I selected... It got me in the right direction.
<script>
Event.observe(window, 'load', function() {
$$('a').each(function(e) {
e.writeAttribute('target', '_parent');
});
});
</script>
That's inside the IFrame with the content. It ended up being the most simple solution for the task.
Same domain in the iframe? Yes.
<script type="text/javascript">
function hijacklinks(iframe){
var as = iframe.contentDocument.getElementsByTagName('a');
for(i=0;i<as.length;i++){
as[i].setAttribute('target','_parent');
}
}
</script>
<iframe src="http://example.com/test.html" onload="hijacklinks(this)"></iframe>
Different domain in the iframe? No.
<iframe src="http://www.google.com/search?q=google+happy" onload="hijacklinks(this)"></iframe>
yields a "Permission denied to get property HTMLDocument.getElementsByTagName".
There may be ways around, but at least with simple JavaScript their are some protections against iframes mucking with sites (imagine a malicious frame around a bank's website and you can understand why).
Use this to create it and you'll have access to any parts with the $body variable:
$(function() {
var $frame = $('<iframe style="width:200px; height:100px;">');
$('body').html( $frame );
setTimeout( function() {
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html('<h1>Test</h1>');
}, 1 );
});
So you can then do something like this
$('a', $body).attr('target', '_parent');
Found here: http://groups.google.com/group/jquery-en/browse_thread/thread/fb646741a6192540
Simplest answer:
<head>
<base target="_blank">
</head>
I got around the cross domain issue via ajax..
function runAjaxDone(response) {
$('body').html(response);
}
function callAjax(url) {
$.ajax({ url: url + '&r=' + Math.random(), success: runAjaxDone });
return false;
}
<a runat="server" href="#"
onclick='<%# "callAjax(\"http://partners.thevoiceinternet.com/portal/Customer/Report/AgentReport.aspx?AgentID="+Eval("AgentID").ToString()+"&name="+Server.UrlEncode(Eval("SubAgentName").ToString())+"\"); return false;" %>'>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("SubAgentName") %>'></asp:Label></a>
Since the parent frame cant be accessed, I replaced the body via ajax.