Display pages source in iframe? - iframe

This might be one of the more daft questions to ask,
but since
<iframe src="view-source:https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Daymusic.html" width="800" height="600"></iframe>
doesn't work:
Is it possible to display a page's source inside an iframe?
(Or any other way really ??)
CLARIFICATION:
I know about the browsers built in "view source" function.
I want the page source being rendered without user interaction.

You could use javascript to fetch the page in question and escape the html.
As an example try using JQuery:
$.get('https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Daymusic.html', function(data) {
var x = document.createElement("pre");
x.id = "test"
$("body").append(x);
$("#test").text(data);
});
Or another example with iframe

Related

Open iFrame in new window with specific size and position

Newbie question here. I have searched a lot and found different parts of the solution but I cannot work out how to put everything together. I hope you can help me.
I need to add a link to my site which will open a new window with specific size in the bottom right corner of the screen. I found this code doing exactly that:
<a onClick="openWindow(); return false;"http://www.example.com">Ask your question!</a>
<script>
var topsss=screen.height-500;
var left=screen.width-400;
function openWindow() {
window.open("http://www.example.com", "_blank", "toolbar=no,scrollbars=yes,resizable=yes,top="+topsss+",left="+left+",width=400,height=500");
}
</script>
Within the new window I don't want to show mysite.com but I need an iFrame showing the content.
I managed to get a new window with the iFrame but the content is not showing in the iFrame:
<script>
function myFunction() {
var myWindow = window.open("", "MsgWindow", "width=420,height=515");
myWindow.document.write('<iframe width="400" height="500" src="http://www.example.com"
frameborder="1" allowfullscreen></iframe>');
}
</script>
Can you help me to put this all together and make this work?
Thanks for your help!
//Manon
I guess that you want to display a form for the user to fill, instead of opening new page for that.
Would it be possible to contain that form/page for all of your pages and have CSS trick to show/hide it? I know it's not what you are asking but the iframes and new pages could just cause you problems, cross-domain-scripting, and overall iframe is controversila (some consider it dead and deprecated by html5). So there might be a more elegant way to do the same with just CSS/JS, you can do more conditions, more controls where it will be placed and what it will do (animations, effects, some interaction with your original page).
https://allyjs.io/tutorials/hiding-elements.html
If you are making a SPA style website then maybe you are not aware of SPA frameworks? There is a lot of JavaScripts frameworks doing these things for you:
https://en.wikipedia.org/wiki/Single-page_application

How to change img src on document ready before browser downloads images?

On my page I have some images on thisdomain.com/images. on document.ready(), I change the src attribute of images to thatdomain.com/images. Firebug's Net tab shows me that images are downloaded from both thisdomain.com and thatdomain.com. How can I prevent the browser from downloading images from thisdomain.com?
$(document).ready(function(){
$("img").each(function() {
var $img = $(this);
var src = $img.attr("src");
$img.attr("src", src.replace(/thisdomain.com.com\/images/i, "thatdomain.com\/images"));
});
});
EDIT: ASP.NET server-side override of Render() using code "in front" i.e., <script runat="server"> I just added this to the aspx page without recompiling code-behind. It's a bit hack-ish but it works.
<script runat="server">
static Regex rgx = new Regex(#"thisdomain.com/images", RegexOptions.Compiled | RegexOptions.IgnoreCase);
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
{
base.Render(htmlwriter);
string html = htmlwriter.InnerWriter.ToString();
string newHtml = rgx.Replace(html, "thatdomain.com/images");
writer.Write(newHtml.Trim());
}
}
</script>
This sounds like something that is impossible to achieve reliably, because images will start to load asynchronously as soon as a src has been specified.
I can't think of a workaround. The <base> tag would allow for some kind of "mass redirection" but the URIs would have to be relative ones for that to work.
I'm sure you have your reasons for outputting thisdomain.com in the first place, but I'm pretty sure you'll have to change your code so thatdomain.com gets output instead (or no src gets specified at all so you can add them using jQuery) if you want a 100% watertight solution.
This ain't going to work in the client side. Your best bet is a server side solution. Have the server side script (PHP? JSP? ASP? etc) to read the to-be-included HTML source and replace the src's accordingly with help of a decent DOM parser before it get emitted to the client side.
I don't that is possible at all. To use jQuery functions, the jQuery library needs to be downloaded, which probably means the browser already started downloading other assets, such as images.
You can't be completely sure to prevent downloading by changing the URL after the element has been parsed. The closest possible that you can get is by changing it immediately after the element:
<img id="something" src="http://www.thisdomain.com/images/hello.gif" />
<script type="text/javascript">
var $img = $('#something');
$img.attr("src", $img.attr("src").replace(/thisdomain.com\/images/i, "thatdomain.com\/images"));
</script>
I don't think there is a way to halt GET requests from img elements once the page has loaded. It's difficult to suggest an alternative since I'm not sure what you're trying to achieve.
Can you be more specific?

Is there an event to detect URL change inside an iframe?

Let say, I have an iframe like that:
<iframe src='test.html'></iframe>
and in test.html, there is a button that will change its url to ...let say google.com
so, is there any way that the iframe knows there is a change in the src?
e.g. onchange or onload.. or whatever.
First of, know the facts about cross-domain policy.
Secondly, if you have control of the child iframe, you can write a script to inform it's part frame (window).
If you have control of the iframe content, you could insert a script setting an action on onbeforeunload event, like so:
<script type="text/javascript">
self.onbeforeunload = function() {alert('unloadevent in frame window');};
</script>
Be aware that onbeforeunload only works in IE and Firefox though, as far as I know.

How do I access a DIV from javascript, if ASP.NET mangles its ID?

I have a web page that contains a "div" element. On the page, there is javascript to reference the div: document.getElementById('divId'). This was working fine until another developer redesigned the page to use an ASP master page.
Now, document.getElementById('divId') returns null. It appears that ASP.net prepends some characters to the names of elements within contents forms when you use a master page. How can I know what the id of the div is when the page loads?
Update Allow me to give a specific example to clarify the question: My page had a div with ID divNotice. After changing my page to use a master page, I see when I print the source to the page that renders that the div ID is ctl00_ContentPlaceHolder1_divNotice. My question is, how am I supposed to know what the div ID is going to be when the framework is done with it?
I think that this is what you looking for.
document.getElementById('<%=divNotice.ClientID%>')
to get the ID of your element as appears on the html page use .ClientID
Hope this help.
Dynamically create the javascript using Control.ClientID to determine the calculated ID of div.
document.getElementById('<%= DivControl.ClientID %>')
Or search for the element on the client side using the base ID as a search pattern. See here: A generic way to find ASP.NET ClientIDs with jQuery
I prefer the server side calculation, but if you don't do it often and/or your current design prohibits it, the client side way is a reasonable workaround.
you can check i the element exists by checking if it returns not null
if (document.getElementById('divId') != null) { /* do your stuff*/ }
in other words:
if (document.getElementById('divId')) { /* do your stuff*/ }
now you have edited you orginal question i got it.. i would do something like this:
var arrDivs = document.getElementsByTagName('div'),
strDivName = "divId";
for (i=0;i<=arrDivs.length;i++){
if( arrDivs[i].id.indexOf(strDivName) != -1) {
alert("this is it")
}
}
you can see a demo here:
http://jsfiddle.net/pnHSw/2/
i think you could do it better with a regex.
But this is a pure JS way i don't know ASP.net
edit: i think Aristos solution is much cleaner :P
maybe you can use a descendent selector un css
<div id="wrapperControler">
<controler id="controler"></controler>
</div>
wrapperControler controler{
dosomething;
}

Using CSS to affect div style inside iframe

Is it possible to change styles of a div that resides inside an iframe on the page using CSS only?
You need JavaScript. It is the same as doing it in the parent page, except you must prefix your JavaScript command with the name of the iframe.
Remember, the same origin policy applies, so you can only do this to an iframe element which is coming from your own server.
I use the Prototype framework to make it easier:
frame1.$('mydiv').style.border = '1px solid #000000'
or
frame1.$('mydiv').addClassName('withborder')
In short no.
You can not apply CSS to HTML that is loaded in an iframe, unless you have control over the page loaded in the iframe due to cross-domain resource restrictions.
Yes. Take a look at this other thread for details:
How to apply CSS to iframe?
const cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['frame1'].contentWindow.document.body.appendChild(cssLink);
// ^frame1 is the #id of the iframe: <iframe id="frame1">
You can retrieve the contents of an iframe first and then use jQuery selectors against them as usual.
$("#iframe-id").contents().find("img").attr("style","width:100%;height:100%")
$("#iframe-id").contents().find("img").addClass("fancy-zoom")
$("#iframe-id").contents().find("img").onclick(function(){ zoomit($(this)); });
Good Luck!
The quick answer is: No, sorry.
It's not possible using just CSS. You basically need to have control over the iframe content in order to style it. There are methods using javascript or your web language of choice (which I've read a little about, but am not to familiar with myself) to insert some needed styles dynamically, but you would need direct control over the iframe content, which it sounds like you do not have.
Use Jquery and wait till the source is loaded,
This is how I have achieved(Used angular interval, you can use javascript setInterval method):
var addCssToIframe = function() {
if ($('#myIframe').contents().find("head") != undefined) {
$('#myIframe')
.contents()
.find("head")
.append(
'<link rel="stylesheet" href="app/css/iframe.css" type="text/css" />');
$interval.cancel(addCssInterval);
}
};
var addCssInterval = $interval(addCssToIframe, 500, 0, false);
Combining the different solutions, this is what worked for me.
$(document).ready(function () {
$('iframe').on('load', function() {
$("iframe").contents().find("#back-link").css("display", "none");
});
});
Apparently it can be done via jQuery:
$('iframe').load( function() {
$('iframe').contents().find("head")
.append($("<style type='text/css'> .my-class{display:none;} </style>"));
});
https://stackoverflow.com/a/13959836/1625795
probably not the way you are thinking. the iframe would have to <link> in the css file too. AND you can't do it even with javascript if it's on a different domain.
Not possible from client side . A javascript error will be raised "Error: Permission denied to access property "document"" since the Iframe is not part of your domaine.
The only solution is to fetch the page from the server side code and change the needed CSS.
A sort of hack-ish way of doing things is like Eugene said. I ended up following his code and linking to my custom Css for the page. The problem for me was that, With a twitter timeline you have to do some sidestepping of twitter to override their code a smidgen. Now we have a rolling timeline with our css to it, I.E. Larger font, proper line height and making the scrollbar hidden for heights larger than their limits.
var c = document.createElement('link');
setTimeout(frames[0].document.body.appendChild(c),500); // Mileage varies by connection. Bump 500 a bit higher if necessary
Just add this and all works well:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
If the iframe comes from another server, you will have CORS ERRORS like:
Uncaught DOMException: Blocked a frame with origin "https://your-site.com" from accessing a cross-origin frame.
Only in the case you have control of both pages, you can use https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage to safely send messages like this:
On you main site(one that loads the iframe):
const iframe = document.querySelector('#frame-id');
iframe.contentWindow.postMessage(/*any variable or object here*/, 'https://iframe-site.example.com');
on the iframe site:
// Called sometime after postMessage is called
window.addEventListener("message", (event) => {
// Do we trust the sender of this message?
if (event.origin !== "http://your-main-site.com")
return;
...
...
});
Yes, it's possible although cumbersome. You would need to print/echo the HTML of the page into the body of your page then apply a CSS rule change function. Using the same examples given above, you would essentially be using a parsing method of finding the divs in the page, and then applying the CSS to it and then reprinting/echoing it out to the end user. I don't need this so I don't want to code that function into every item in the CSS of another webpage just to aphtply.
References:
Printing content of IFRAME
Accessing and printing HTML source code using PHP or JavaScript
http://www.w3schools.com/js/js_htmldom_html.asp
http://www.w3schools.com/js/js_htmldom_css.asp

Resources