Parsing iframe HTML code to get just the src attribute - javascript

I want to be able to take Iframe HTML code like the following...
<iframe src="https://example.com" width="100" height="100"></iframe>
and from it just get the src attribute: https://example.com
I will need to get the src attribute in javascript.
I have tried doing the following:
var iframeCode = `<iframe src="https://example.com" width="100" height="100"></iframe>`
document.getElementById("tmpElement").outerHTML = iframeCode
var src = document.getElementById("tmpElement").childNodes[0].src
It works, but there is a security flaw with this approach. If the page I set in the iframe code contains javascript, it would execute. While this is normal behaviour, I need help to find a solution which will either not execute the javascript or get the src without loading the iframe (this may be possible with regex, possibly?, but I am no expert at regex.)
Thank you in advance.

You could use DOMParser, which can turn an HTML string into a document without any possibility of executing unsafe code (like scripts or inline handlers):
const str = '<iframe src="https://example.com" width="100" height="100"></iframe>';
const doc = new DOMParser().parseFromString(str, 'text/html');
console.log(doc.body.children[0].src);

Related

Cannot add JavaScript code into existing iFrame using jQuery

I tried some ways to be able to interact with the iframe but cannot add js to iframe
My code use iframe with the source:
<div class='roomle-configurator--wrapper'>
<iframe id="frRoomle" src="https://www.roomle.com/t/cp/?configuratorId=delife&id=delife:product_test_1&api=false" width="1024" height="768"></iframe>
</div>
I use the below code but it doesn't work, I think the issue is caused blocking by src https://www.roomle.com
var script = "alert('hello world');";
$('#frRoomle').contents().find('body').append($('<script>').html(script))

Node JS Get all iframes from url

I have a static webpage which I can't change and I need to get all iframes on this page. The iframes have no id's or name. They look like this
<iframe height="584" width="630" src="someurl" scrolling="auto" noresize="" frameborder="0"></iframe>
So, I can get the "main page" content with the module request but I don't know how to loop through it and find all iframe elements and their sources!
Hope you can help,
dunklesToast
The node module called cheerio is a node-like jQuery alternative. You can load your content of the "main page" and then get all the iframes like this:
var cheerio = require('cheerio')
var $ = cheerio.load(mainPageContent);
$('iframe').each(function(index, element) {
var url = $(element).attr('src'); // --> Get the URL of the iframe
// Do something with the URL of the iframe here
});

how do i load a view(cshtml) into an iframe?

I'm trying to load a view into an iframe in another(parent) view using javascript and razor.
I'v tried setting the iframe's src to this
var url = '#Url.Action("myaction", "MyController")';
and this:
var url = '#Href("~/myform.cshtml")';
without success.
Thanks
Thanks
If you are using razor engine.
<iframe src = '#Url.Action("myaction", "myController")' width = "100%"
height="1000" frameBorder="0"></iframe>
Set the 'src' attribute of the iframe to the action's url.
Example:
<iframe src ='home/index'></iframe>
Make sure you replace the URL within the src attribute to the URL of the action.
An alternative way in Razor:
<iframe src ='#Url.Action("action name")'></iframe>

Javascript function return src path

I'm trying to set an 'src' by calling a javascript function that returns the path like so:
<img src="getImagePath()" />
the function:
function getImagePath(){
return "images/image1.png";
}
But it doesn't seem to work. Anything I'm missing? Thanks to anyone pointing me in the right direction.
The src attribute takes an URL, not JavaScript. You might want to try
<img src="pixel.gif" onload="this.onload=null; this.src=getImagePath();" />
You can't do this. The src attribute of an img element can't be interpreted as javascript when the html is interpreted.
But you may do this :
<img id=someImage>
<script>
function getImagePath(){
return "images/image1.png";
}
document.onload = function(){
document.getElementById('someImage').src=getImagePath();
};
</script>
Building on Eugen's answer, I wanted something self-contained (no id's, as inline as possible) that would not require a hosted pixel.gif image. I came up with a few possibilities:
One option would be to use a base64 encoded src URL instead (as small as possible). Note that data-uris are supported in IE8+:
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" onload="this.onload=null; this.src=getImagePath();">
See it in action on jsfiddle.
A second option would be to use document.write to write the image tag directly with an inline script. Just put the below <script> instead of the <img>. Note that many consider document.write to be bad practice:
<script>
function getImagePath() {
return "http://i.imgur.com/4ILisqH.jpg";
}
document.write('<img src="'+getImagePath()+'">');
</script>
See it in action on codepen.io.
A third (perhaps even more hackish) option would be to forcibly break the image by supplying a null src, and (ab)use the onerror callback.
This works in IE11 and Chrome, but not Firefox:
<img src onerror="this.onerror=null; this.src=getImagePath();">
See it in action on jsfiddle.
This fourth option relies on a simple function that sets an <img> tag followed immediately by an inline <script> that sets the image's src via JavaScript:
<!-- In the <body> -->
<img><script>set_most_recent_img_src(getImagePath())</script>
And in your <head>:
<!-- In the <head> -->
<script>
function getImagePath() { return "https://www.gravatar.com/avatar/71ec7895cada78741057c644d858b0e3"; }
function set_most_recent_img_src(val) {
var a = document.body.getElementsByTagName('IMG');
var img = a?a[a.length-1]:0;
if (img) img.src = val;
}
</script>
See it in action on codepen.io.
Summary: I'm just ideating. Each option has different implications and requirements -- they're all workarounds, and should be tested thoroughly for your specific use case. Personally I think the first option (base64 URI) is the most solid (if you ignore old IE browsers, which I happily can).
https://stackoverflow.com/a/17229404/487771
<script type="text/javascript">
var country = $("#SCountry").val();
document.getElementById("iframeid").setAttribute("src","https://domain.com/country="+country)
</script>

Open iframe page in parent frame (javascript)

I'm sure someone in the know has a solution to this problem I'm facing? I have a site with Index.html which contains an Iframe. In this iframe, all pages of the site are shown...Home.html..Info.html...Contact.html..etc.
I'd like a javascript function so that when you open Home.html via the google sitemap for example, it shows up in the parent frame in Index.html. The function I currently have in the head section of each child page is:
<script>
if (parent.location.href == self.location.href){
window.location.href = 'index.html'
}
</script>
Although this works, it doesn't remember the child page and opens the Index page with the default iframe page...Home.html as the iframe is coded like this:
<iframe id="iframe" src="home.html" allowTransparency="true" id="iframeID" name="iframeID" width="100" height="100" scrolling="no" frameborder="no">
</iframe>
Has anybody a solution to this problem, as I've searched everywhere? Thanks.
Try to set location.href with a query string, i.e.:
// .getAttribute so we don't get the absolute URL
var src = document.getElementById("iframe").getAttribute("src");
if (parent.location.href === self.location.href)
location.href = "index.html?" + escape(src);
In index.html create a check for query strings and set the iframe source accordingly:
if (location.search)
document.getElementById("iframe").src =
unescape(location.search.substring(1));

Categories

Resources