Javascript/jQuery - Check iframe is on another domains - javascript

I have a script which handles something in content of the frames. I want to except iframe from another domains (cross-domains) or filter iframe of same domain.
function isCrossDomain(ifr) {
// what i need
// Return true or false
}
if (! isCrossDomain(ifr)) {
var doc = ifr.contents();
}

<iframe name="myFrame" id="myFrame" src="child.html" style="height: 50%; width: 50%;" onload="checkForCross()"></iframe>
function checkForCross()
{
var iframe = document.getElementById("myFrame");
var loc = iframe.contentDocument.location.href;
}

I hope I am understanding you correctly. Just collect the iframes that match your conditional. Lets just say in this case, its yourdomain.com
Once you have your collection of matches, then you can extract the contents() from them.
You can create a regex to capture the match you want.
var iFRMS = jQuery('body').find('iframe').map(function(n, i){
if (jQuery(i).prop('src').match('yourdomain.com')){
return this;
}
});

Related

Replacing iframe source with Javascript - Can I use a loop?

I have a list of items (districts) on a page, and an iframe pulling in a map on the same page. When a user clicks on one of the districts, the JavaScript changes the source of the iframe to show a map of the district the user clicked.
My current code simply uses an "onclick" for each district, which then calls a function to change the source of the iframe.
I am wondering if I can simplify this code at all, possibly by using a loop? If I have 15 more districts to add to the page, will I have to add another "onclick" and another function for each one? Or is there an easier way that I am missing?
Simplified HTML:
<div id="districtlist">
Allen
Barren
Butler
<!--about 15 more links to follow-->
</div>
<iframe id="maparea" src="http://www.reddit.com"></iframe>
Javascript:
var a = document.getElementById("districtlist")
a.getElementsByTagName("a")[0].onclick = Allen;
a.getElementsByTagName("a")[1].onclick = Barren;
a.getElementsByTagName("a")[1].onclick = Butler;
//more lines...
function Allen() {
document.getElementById("maparea").src="http://www.youtube.com";
}
function Barren() {
document.getElementById("maparea").src="http://www.mentalfloss.com";
}
function Butler() {
document.getElementById("maparea").src="http://www.amazon.com";
}
//more functions...
I believe you could try this
var elems = document.getElementById("districtlist").querySelectorAll('a');
[].forEach.call(elems, function(elem) {
elem.onclick = function() {
var url = '';
switch(elem.innerText) {
case 'Allen':
url = "http://www.mentalfloss.com";
break;
case 'Barren':
url = "http://www.mentalfloss.com"
break;
case 'Butler':
url = "http://www.amazon.com";
break;
}
document.getElementById("maparea").src=url;
}
});

Iframe src attribute change with parameter

I’m trying to change the src attribute of an <iframe> depending if the iframe src has /?foo or not.
I had this solution:
<script>
jQuery(document).ready(function($) {
$('iframe[src*="?foo"]').each(function() {
$('#frame').attr('src', "http://www.example.com/page2");
});
});
</script>
<iframe id="frame" src=„www.example.com/page1/?foo"></iframe>
But my problem is that I have no access to the page, where the iframe is emded so I can't write this code into the <head> of the site.
I have access to both pages www.example.com/page1 and www.example.com/page2
I don’t know how I need to change the code to manipulate the src.. I am not sure if this is even possible, when I have no access to the page with the iframe
As seen in How to retrieve GET parameters from javascript? you can use the following code and call the function parseSecond("foo") to get the foo parameter on page1. You can find more information about this on the question page.
function parseSecond(val) {
var result = "Not found",
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
}
return result;
}
If you then want to redirect to page 2 you can write the following code to redirect the frame from page1 to page2 when the foo parameter has the value equal to bar.
if(parseSecond("foo")=="bar"){
window.location="www.example.com/page2";
}

Displaying a specific page of PDF inside iframe in Asp.net

I have an ASP.NET C# application. I am displaying a PDF file at a specific page inside an iframe. I need to display a specific page of PDF based on a text box value. How can I achieve this ?
The iframe code looks like this:
<iframe runat="server" id="lobjPDFObj" height="600" width="800" > </iframe>
and following is the the details of the text box
<asp:TextBox ID="txtTo" runat="server" Text="1" class="page_txtbox" onfocus="synchronizePDF(this);" ></asp:TextBox>
Details of javascript function
function synchronizePDF(Field) {
//parent.document.getElementById('lobjPDFObj').setCurrentPage(Field.value);
var childiFrame = parent.document.getElementById('lobjPDFObj');
var URL = childiFrame.contentWindow.location.href;
//var URL = childiFrame.src;
var pos = URL.indexOf('#page');
if (pos < 0) pos = URL.length;
var result = URL.substring(0, pos);
if (URL != 'about:blank') {
result += '#page=' + Field.value;
}
childiFrame.contentWindow.location.reload(true);
childiFrame.contentWindow.location.href = result;
//childiFrame.src = result;
//parent.document.getElementById('lobjPDFObj').setAttribute("src", result);
}
But this is not working. It is giving error at "childiFrame.contentWindow.location.href" as The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "https". Protocols must match.
How can i get rid of the error? And i am passing page no as a paramter in the url. How can i show the new page without refreshing entire content?
As stated here: The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match and here: Error trying to access a iframe in JavaScript the iframe can show content from other side, but you cannot change it in any way, because it would cause security risk. If you want to change the content of the iframe it source must come from same domain (refer to CORS for more reference).
Another way is to allow Cross-Origin Resource Sharing for other domains. In order to do that you need to specify special header:
Access-Control-Allow-Origin: https://www.test-doc.com
More info about this topic: http://enable-cors.org/server_aspnet.html, http://docs.asp.net/en/latest/security/cors.html.
In both methods shown below, a local PDF is opened in an iframe, at the selected page number, when the focus leaves the TextBox.
Method 1
In this method, the iframe source URL is set in two steps. The first step resets the source, the second sets it to the actual URL. This second step has to be performed asynchronously in order to work (here with the help of setTimeout).
The markup for the iframe and the TextBox:
<iframe id="iframePdfViewer" name="iframePdfViewer" width="700px" height="700px" ></iframe>
<asp:TextBox ID="txtPageNumber" runat="server" Text="1" onchange="showPDF(this.value);" />
The Javascript function:
function showPDF(pageNumber) {
var iframe = document.getElementById("iframePdfViewer");
iframe.src = '';
setTimeout(function () { iframe.src = 'MyFolder/MyDoc.pdf#page=' + pageNumber }, 0);
}
Method 2
In this method, the iframe is replaced by a new one each time a new page of the PDF is to be displayed. In order to reduce screen flicker: (1) the new iframe is inserted under the old one, and (2) the old iframe is removed only when the new one is fully loaded.
The markup:
<div id="divPdfViewer" style="position: relative; width: 700px; height: 700px;"></div>
<asp:TextBox ID="txtPageNumber" runat="server" Text="1" onchange="showPDF(this.value);" />
The Javascript code:
function showPDF(pageNumber) {
var divPdfViewer = document.getElementById('divPdfViewer');
var ifrm = document.createElement("IFRAME");
ifrm.id = 'iframePdfViewer';
ifrm.style.position = 'absolute';
ifrm.style.width = '100%';
ifrm.style.height = '100%';
var oldPdfViewer = divPdfViewer.firstChild;
if (oldPdfViewer) {
ifrm.onload = function () { divPdfViewer.removeChild(oldPdfViewer); };
// Replace the line above by the line below if support for IE is required
// setTimeout(function () { divPdfViewer.removeChild(oldPdfViewer); }, 100);
divPdfViewer.insertBefore(ifrm, oldPdfViewer);
}
else {
divPdfViewer.appendChild(ifrm);
}
ifrm.setAttribute("src", 'MyFolder/MyDoc.pdf#page=' + pageNumber);
}

Return ID of all iframes in a page

Because of the widget format I'm working with I have a page which has multiple iframes embedded within iframes. I won't paste the code as it's vast and unwieldy but it is essentially just this:
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
blah
</body>
</html>
</iframe>
</body>
</html>
</iframe>
</body>
</html>
</iframe>
</body>
</html>
However, there may be more - or less - iframes dependent upon the page and template I use.
I'm trying to therefore get the ID of all of the iframes in this page, from within the most-embedded iframe.
Is this possible with jQuery? I've tried a few snippets of code but had no luck:
$('iframe', window.parent.document).each(function() {
console.log($(this).attr("id"));
});
$('iframe', parent.document).each(function() {
console.log($(this).attr("id"));
});
$('iframe').each(function() {
console.log($(this).attr("id"));
});
The output of these is a single ID string - and unfortunately it's not the iframe I'm looking to control.
Thanks in advance,
EDITED
This returns an iframe element which has the wanted id, and null, if the wanted id is not found.
function searchIds(wantedId) {
var idArray = [], n,
search = function (iframes) {
var n;
for (n = 0; n < iframes.length; n++) {
if (iframes[n].frames.length > 0) {
search(iframes[n].frames);
}
idArray.push(iframes[n].frameElement.id);
idArray.push(iframes[n].frameElement);
}
};
search(window.top.frames);
for (n = 0; n < idArray.length; n += 2) {
if (idArray[n] === wantedId) {
return idArray[n + 1];
}
}
return null;
}
Notice, that searchIds() can't be run before onload of the main window has been fired.
I do not believe you can reference the iframe's children directly. You will need to recursively search each iframe using it's .contents() call.
As far as I know, this will only work as long as the same-origin policy is not violated (i.e. the iframes must point to the same domain).
From the most embedded iframe:
var ids = (function up( context, ids ){
ids = ids || [];
// proceed if we're not at the top window yet
if( context !== window.top){
// point context to parent window (or top if no parent).
context = context.parent || window.top;
// get the id of the first iframe in parent window;
// this will break if there are sibling iframes
ids.push(context.document.getElementsByTagName('iframe')[0].id);
// recursive call to traverse parents
return up(context, ids);
} else {
// otherwise return the list of ids
return ids;
}
}(this)); // 'this' is the initial context - current window
console.log( ids );

Javascript to Remove Elements loaded in iFrame

After searching Google and Stack Overflow I decided to ask if this is even possible.
Currently I am loading an iFrame on my site. I wish to hide a certain element loaded in the iFrame.
<span id="blahblah">
function collapseAll(){
var body = document.getElementById('body');
var spans = body.getElementsByTagName("span");
var span;
for (i = 0; i < spans.length; i++){
span = spans[i];
if(span.class=='blahblah'){
span.style.visibility = "hidden";
}
}
}
However this did not work. Question number one is can this be done? If yes could you explain how?
Thank you kindly.
You'll have to put that script inside the contents of the iframe. You can't access the DOM of another frame, especially if it's from another domain.
Sorry, but you cannot access elements within an iframe from the outer window, due to security controls.
You would have to try this, but you might be able to create a function on the window object of the iframe and the call it from the outer window.
In the iframe:
<script type="text/javascript">
window.collapseAll = function() {
.....
}
</script>
In the outer window:
<script type="text/javascript">
function doCollapse() {
document.getElementById('my_iframe").window.collapseAll();
}
</script>
Again, that's untested but I'm pretty sure Facebook does something similar to that.
if the iframe is from the same domain as your javascript is from then this is doable.
using plain javascript you would write the following
`
function collapseAll(){
var body = document.getElementById('body');
var spans = body.getElementsByTagName("span");
var span;
for (i = 0; i < spans.length; i++){
span = spans[i];
if(span.class=='blahblah'){
**span.style.display = "none";**
}
}
}
this fixes the issue.
if the iframe is from a different site (domain) then things would get really difficult..
there are solutions like greasemonkey which can operate on pages from different domains.
you can try
document.frame.document.getElementsByTagName('span')
<script type="text/javascript">
function remove_elemment() {
var body = document.getElementById('body');
var divs = body.getElementsByTagName("div");
var div;
for (i = 0; i < divs.length; i++){
div = divs[i];
if(div.class=='buybox'){
**div.style.display = "none";**
}
}
};
function doRemove() {
document.frame.document.getElementById('my_iframe').remove_elemment();
}();
</script>
<div class="floating-widget">
<iframe id="my_iframe" src="http://www.nodebeginner.org/index-vi.html" frameborder="0" width="100%" height="500">
</iframe>
</div>

Categories

Resources