get content of iframe from another domain - javascript

I have an iframe from another domain. Since It's not possible to edit anything I want to read the content of the iframe.
The iframe has 4 pages. On the fourth page there is some text(example:"It's done"). I want to write something to a MySql database if the text appears in the iframe.
To accomplish this I need two things. 1. Read the contents of the iframe. 2. Execute this code part every X milliseconds to find the text I'm searching for.
1: var iframe = document.querySelector('#id_description_iframe');
var iframeContent;
if (iframeDocument) {
iframeContent = iframeDocument.querySelectorAll('#frameBody');
}
2: window.setInterval(function_name, 10000);
I was wondering if this doesn't conflict with the same origin policy?
Second thing I was wondering about: How do I then write this to mysql database?
1: Make another page that receives a value throught GET method.
2: By the JS on the iframe page call another tab if the text has been found. The url would be the get url.
3: There save it to the mysql database.
4: after page loaded close tab again.
Really hope someone can help me out. Excuse me if the question isn't clear since I did really try to make it a really clear question.

Get all content of other site:
var pageContent, iframe, iframeContent, iframeUrl = null;
pageContent.load(<url>);
iframeContent = pageContent.find('iframe')[0];
iframeUrl = iframeContent.attr('src');
iframe = pageContent.load(iframeUrl);
Then, the content of iFrame is read to use on 'iframe' variable.

Related

Check if the element inside an iFrame has any content

So I've tried to do a bunch of research and can't seem to find the correct answer for my question so I wanted to reach out and see if anyone knows much.
What I'm attempting to achieve:
Check the contents inside an iFrame and return a boolean whether there is content or not.
Here is what I've attempted:
function check_iframe_body_content(element) {
let has_content = false;
let iframe = element.contents().find('body');
console.log(iframe);
if (iframe.length > 0) {
has_content = true;
}
return has_content;
}
The element is the iFrame return, which will be an array:
When the script tags are disabled, I get the following return:
When the script tags are enabled, I get the following return:
How can I properly determine if the <body> is empty and when it's not? I've tried to do .length on multiple different occasions and each time it comes back as has_content = true because it finds the body element, but it's actually empty.
All help will be appreciated!
You wont have access to the content inside iframe if it's loaded from another website as it's a major security breach.
if that was possible a website could add an iframe to google.com and get access to user personal information like their email address, name and etc.
depending on why you want to check content of iframe, there might be other workarounds.

How to capture the displayed link in HTML (JavaScript) and pass to another HTML page as a variable?

I am building a website (and I am a novice) and the site has 2 frames. On the left side (frame 1), I have a list of links that when you click on a link it will load a page in frame 2 (right side). But the links are on the left side are actually the result of a query and will change.
Rather than hard coding a site for each link, I want to use one target page to display data. I want to use the link on the left side as a variable value to pass to the right side so I can use the link name in a query on the target page.
MyUniqueLink
Any help would be very appreciated.
In your first <iframe>, you can access the parent document like so:
// window.parent will be undefined if you are not in an iframe.
window.parent.document
Then, as spencer said, it would be easier for you to use document.getElementById("secondFrameId") to get to your second iframe.
Also, the onclick event might be a bit more suited to your needs.
So together the code would look like:
<a onclick="window.parent.document.getElementById('secondFrameId').src='http://example.com'">MyUniqueLink</a>
If you want to access the data in your <a>'s, you should start by giving them an id:
<a id = "myId" href="JavaScript:void(top.frames[2].location.href='Recap.html');" >MyUniqueLink</a>
Then you can grab their data using standard js:
document.getElementById("myId").innerHTML; // grabs MyUniqueLink
document.getElementById("myId").getAttribute("href"); // resolves to href value
Or accomplish the same using jQuery:
$("#myId").html();
$("#myId").attr("href");
If you are dynamically creating the <a>'s in the first place, you can also assign them an id at this point using newElement.setAttribute("id", "someNewId");.

Get current object URL with JavaScript

I have a webpage uses object that are external websites (or other web pages).
for example:
<object data="external.html"></object>
on this page (external.html), the URL changes according to the navigation of the user. I want to know if there's a way to get the new URL using JavaScript/jQuery.
For example, when using:
<object data="www.google.com"></object>
If the user went from www.google.com to www.google.com/#q=JavaScript, I would like to get the second URL.
This won't work with Google, but theoretically speaking.
Alternatively, is there a way to display an external website and have access to the changing URL? Meaning, having a div populated by another website and somehow get the URL (after the user navigated through the site and the URL changes) with JavaScript/jQuery/some other way?
No need to manipulate this URL, just read access.
You can collect current URL using location.href and then collect object using its ID and then append data as current URL to it.
This should not possible as it will violate cross domain security policies. The same restriction is there with iframe, so I guess it applies to object as well.
If it is same domain, you can try getting the current URL from contentWindow or contentDocument
<objectElement>.contentWindow.location.href
Hope this is what you are looking for. You can split the url.
$('button').click(function() {
var urlSplit = 'www.google.com/#q=JavaScript'.split('/');
alert(urlSplit[urlSplit.length - 1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Click Me
</button>
$('button').click(function() {
var urlSplit = 'www.google.com/#q=JavaScript'.split('/');
alert(urlSplit[urlSplit.length - 1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Click Me
</button>

How to switch between original DOM and the DOM changed by a Content script?

I'm making a Chrome Extension that changes the DOM of a page. But I would like to give the user an option to switch between the page before the changes and the changed page.
It's a little bit like Google translate where you can change between the orginal language and the translated message.
I could not find anything in my own searches.
I know JavaScript but not JQuery yet.
Thanks for the help.
You could save the entire body in a variable, then start overwriting things. If you want to switch back load up the old body.
You could save all the original DOM content to a variable before running the content script. You can do this by using the following code at the top of your content script:
var originalDOM = document.getElementsByTagName("*");
This saves the entire DOM in an array called originalDOM. The * acts a universal tag, requesting every tag in the document. You can read more about the .getElementsByTagName() API here.
You could try:
var html = document.getElementsByTagName("html")[0];
var page = html.innerHTML;
This will give you everything between the <html> tags.
After the content script is injected, run:
var newPage = html.innerHTML;
Now, whenever you want to switch between the pages, simply run:
html.innerHTML = page; //or newPage
You can read more about the .getElementsByTagName() API here

Javascript Iframe innerHTML

Does anyone know how to get the HTML out of an IFRAME I have tried several different ways:
document.getElementById('iframe01').contentDocument.body.innerHTML
document.frames['iframe01'].document.body.innerHTML
document.getElementById('iframe01').contentWindow.document.body.innerHTML
etc
I think this is what you want:
window.frames['iframe01'].document.body.innerHTML
EDIT:
I have it on good authority that this won't work in Chrome and Firefox although it works perfectly in IE, which is where I tested it. In retrospect, that was a big mistake
This will work:
window.frames[0].document.body.innerHTML
I understand that this isn't exactly what was asked but don't want to delete the answer because I think it has a place.
I like #ravz's jquery answer below.
Having something like the following would work.
<iframe id = "testframe" onload = populateIframe(this.id);></iframe>
// The following function should be inside a script tag
function populateIframe(id) {
var text = "This is a Test"
var iframe = document.getElementById(id);
var doc;
if(iframe.contentDocument) {
doc = iframe.contentDocument;
} else {
doc = iframe.contentWindow.document;
}
doc.body.innerHTML = text;
}
If you take a look at JQuery, you can do something like:
<iframe id="my_iframe" ...></iframe>
$('#my_iframe').contents().find('html').html();
This is assuming that your iframe parent and child reside on the same server, due to the Same Origin Policy in Javascript.
Conroy's answer was right. In the case you need only stuff from body tag, just use:
$('#my_iframe').contents().find('body').html();
You can use the contentDocument or contentWindow property for that purpose.
Here is the sample code.
function gethtml() {
const x = document.getElementById("myframe")
const y = x.contentWindow || x.contentDocument
const z = y.document ? y.document : y
alert(z.body.innerHTML)
}
here, myframe is the id of your iframe.
Note: You can't extract the content out of an iframe from a src outside you domain.
Don't forget that you can not cross domains because of security.
So if this is the case, you should use JSON.
This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(\".navbar\").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}
document.getElementById('iframe01').outerHTML
You can get the source from another domain if you install the ForceCORS filter on Firefox. When you turn on this filter, it will bypass the security feature in the browser and your script will work even if you try to read another webpage. For example, you could open FoxNews.com in an iframe and then read its source. The reason modern web brwosers deny this ability by default is because if the other domain includes a piece of JavaScript and you're reading that and displaying it on your page, it could contain malicious code and pose a security threat. So, whenever you're displaying data from another domain on your page, you must beware of this real threat and implement a way to filter out all JavaScript code from your text before you're going to display it. Remember, when a supposed piece of raw text contains some code enclosed within script tags, they won't show up when you display it on your page, nevertheless they will run! So, realize this is a threat.
http://www-jo.se/f.pfleger/forcecors
You can get html out of an iframe using this code
iframe = document.getElementById('frame');
innerHtml = iframe.contentDocument.documentElement.innerHTML

Categories