Get raw content of Iframe - javascript

I want to use Jquery or javascript to get the raw content (mean everycharacter) of an Iframe. It sounds simple but I'm still struggling with finding the right way for it.
For now it is only a XML content in the Iframe though.
Here the code:
$(function() {
var xmlContent = $("#CFrame").contents().find("*").text();
// The magic
$('#SResult').xslt({xml: xmlContent, xslUrl: 'stylesheet/designSS.xsl'});
});
The html page
<form id="searchForm" method="GET" target="ContentFrame" action="http://125.235.8.210:380/search" onSubmit="processContent()">
.....
</form>
</div>
<div id="SResult">
</div>
<iframe id="CFrame" name="ContentFrame" frameborder="1" height="2000px" width="1000px" scrolling="no" src="stylesheet/test.xml"></iframe>
</body>
Thanks,

Disclaimer: I'll answer your question regardless of whether it is actually an elegant solution to your problem. Joseph seems to take that as the question. I would say he is probably right to do so.
It won't work trying to get the frame using mimetype text/xml. The browser will proceed and 'translate' the XML into HTML. That's why it doesn't sound so simple. This way it is actually impossible.
I present you with a simple work-around for this problem.
<html>
<head>
<script>
function getXmlContents() {
/*
Note: Because of security reasons, the contents of a document can be accessed from another document only if the two documents are located in the same domain.
http://www.w3schools.com/jsref/prop_frame_contentdocument.asp
*/
var iframeDocument = document.getElementById('greetingFrame').contentDocument;
if (iframeDocument == null)
return undefined;
var xmlContainer = iframeDocument.getElementById('xmlContainer');
if (xmlContainer == null)
return undefined;
return xmlContainer.innerText == null ? xmlContainer.textContent : xmlContainer.innerText;
};
</script>
</head>
<body>
<iframe id="greetingFrame" src="helloworld.html" onload="alert(getXmlContents())">
</iframe>
</body>
</html>
The contents of the XML are wrapped inside an HTML (helloworld.html):
<html>
<body>
<script id="xmlContainer" type="text/xml">
<?xml version="1.0" encoding="UTF-8"?>
<title>
Hello world
</title>
</script>
</body>
</html>
I've successfully tested this in Chrome, Firefox and IE.
Of course you would have to wrap your XML documents inside a HTML script tag as indicated above. The XML can also be wrapped in a different tag, if you'd like it rendered for example, but you'd have to encode the XML using html encoding. This needs to be done on the server-side. A very simple (php/ruby/python/etc) script would suffice.

If your XML resides on your domain, you are better off with AJAX, especially using the jQuery library, which parses it for you and make it ready for immediate manipulations.
If it does not live on your domain, then you can't access it via AJAX unless the remote server and your client's browser both support CORS.
You have options though:
If the remote server's API supports JSONP, use it instead of XML. Then you can use jQuery to retrieve JSONP data or roll your own script loader.
Or use your server to proxy the XML for you. Servers are not restricted to the Same Origin Policy. Create an API on your server that relays your form data to the remote server and retrieve the remote page - all as if your server was the browser. Then forward the results back to you.

Related

How to get contents of HTML `object`?

Goal
I want to put a normal tag in my HTML page to grab text from file from a remote file from my own server. Then, javascript will manipulate the text, and display it on the webpage. So JS must be able to grab the contents of the remote file.
The remote file is called "records.html". It's not a complete webpage, just a fragment. It isn't json data.
I prefer a pure HTML solution for pulling the data into the page, if possible.
The remote file is on the same domain as the parent page. It's my html, my JS, my data.
Things i've tried:
object with text/html type
HTML:
<object id="records" type="text/html" data="records.html" ></object>
JS:
window.onload = function getRecords() {
const obj = document.querySelector("#records");
console.log(obj.contentDocument.documentElement.innerText)
};
It fails. I can see the external contents in the browser dev tools, but
the output is blank.
The external HTML file doesn't contain <html>, #document, or <body> tags, but the loaded object content has all those tags. It would be cool to prevent the extra tags, but not critical.
In case it's a race condition, I've read <object> tags don't support an onload event, so i can't get it's contents with a load event.
object with application/json type
This actually works. However, my remote data isn't json. So to use this method, it requires putting non-json data into a file with a .json extension. That seems like very bad form.
<object id="records" type="application/json" data="package.json"></object>
<script>
document.getElementById('records').addEventListener('load', function () {
console.log(this.contentDocument.documentElement.innerText)
})
</script>
link
<link type="text/html" href="records.html">
Doesn't work. I've read this method is deprecated.
iframe
I tried with iFrame but it failed. I may have done it wrong.
XMLHttpRequest + Filesystem API
I believe this has been superceded by JS fetch.
fetch
I haven't had any success wrapping a function around fetch. It's returning a Promise{}, instead of data.
async function fetchText(sURL) {
let response = await fetch(sURL);
let data = await response.text();
return data;
}
contentDocument
For example, this is working for me:
<body>
<object id="records" type="application/json" data="package.json"></object>
<script>
document.getElementById('records').addEventListener('load', function () {
console.log(this.contentDocument.documentElement.innerText)
})
</script>
</body>
If I were doing it, I'd reach for fetch()
<html>
<head>
<title>my neat page</title>
</head>
<body>
<div id="target"></div>
</body>
<script>
const output = document.getElementById("target");
fetch("./myResource.html")
.then((response)=>response.text())
.then((text)=>{/* This is where you manipulate the text response */})
.then((manipulatedText)=>{output.innerHtml=manipulatedText});
</script>
</html>
see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch and https://developer.mozilla.org/en-US/docs/Web/API/Response/text and https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Disable Javascript from cross-domain file

I have an html file which intends to load XHR html files.
Here is my code:
<div id='some-id'></div>
<div id='some-id-2'></div>
<script type='text/javascript'>
$('#some-id').load('some-url');
</script>
My problem is the external html file contains some javascript code which is executed after embedding it. How can I prevent this problem? (The url is cross-domain and I do not have permission to the remote domain server)
Might not be the best solution, but since you can't control the returning data -
You can load only some of the HTML, e.g. only the elements that interest you:
$('#some-id').load('http://www.some-url.com/index.html div#elementId');
Also, like apsillers mentioned, you can exclude the script:
$('#some-id').load('http://www.some-url.com/index.html :not(script)');
Or, you could remove it at return level:
$.get('http://www.some-url.com/index.html', function(data) {
$(data).find('script').remove();
$('#some-id').html(data);
});

HTML5 Video link not working in Chrome

I have the following code for viewing my webcam directly via a publicly accessible link.
<!DOCTYPE html>
<html>
<head>
<title>webRTC Test</title>
</head>
<script type = "text/javascript">
function init()
{
if(navigator.webkitGetUserMedia)
{
navigator.webkitGetUserMedia({video:true}, onSuccess, onFail);
}
else
{
alert('webRTC not available');
}
}
function onSuccess(stream)
{
document.getElementById('camFeed').src = webkitURL.createObjectURL(stream);
var src = document.getElementById('camFeed').getAttribute('src');
document.getElementById('streamLink').href = src;
}
function onFail()
{
alert('could not connect stream');
}
</script>
<body onload = "init();" style="background-color:#ababab;">
<div style="width:352px; height:625px; margin:0 auto; background-color:#fff;">
<div>
<video id ="camFeed" width="320" height="240" autoplay>
</video>
</div>
<div>
<canvas id="photo" width="320" height="240">
</canvas>
</div>
<div style="margin: 0 auto; width:82px;">
<a id="streamLink">Visit Stream</a>
</div>
</div>
</div>
</body>
</html>
The link generated in the anchor tag is something like:
blob:http%3A//sitename.com/7989e43a-334r-4319-b9c5-9dfu00b00cd0
And upon visiting chrome tells me "Oops! This link appears to be broken."
Help appreciated!
The File API spec defines URL.createObjectURL. There are a couple of sections that make what you're trying to do impossible in a browser that follows the spec.
Section 11.5 says:
The origin of a Blob URI must be the origin of the script that called URL.createObjectURL. Blob URIs must only be valid within this origin.
In other words, the URIs returned by createObjectURL can only be used within the context of the website that created them (see RFC6454: The Web Origin Concept for a more precise definition of what the HTML specs mean by “origin”). You can't visit a URL returned by createObjectURL directly.
Section 11.6 says:
This specification adds an additional unloading document cleanup step: user agents must revoke any Blob URIs created with URL.createObjectURL from within that document.
This means that even if you could visit the URL directly, as soon you you leave the page that called createObjectURL the URL that was created ceases to exist.
You must ensure that you’re using/testing your code at HTTP or HTTPs protocols --- because URL.createObjectURL has some issues at file:// protocol --- and it can’t be able to generate right BLOB for your video while using file:// ---- !!!
Your code won't work on localhost or your machine alone.
All you need is, upload this HTML document on the Net(just in case you are wondering on how to get Hosting for yourself, then try checkout Dropbox, you can upload your HTML page publicly and get access via Public Link for free or try some other product or simply get hosting for yourself). As you can see that this example http://www.html5rocks.com/en/tutorials/getusermedia/intro/ works perfectly in chrome, though the code that it is utilising is the same as yours. I hope this solution is of some help to your and others searching for an answer to this bug.
Also, you can then use an iframe to get access to the video element to perform operations on it.

JQuery JSON data not displaying

I am having trouble displaying some jason from a page.
The data is there but I think it might have to do with this line:
document.write(fbResults.cats[0].title);
Here is the full html source:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON('http://mydomain.com/api/get_cats', function(fbResults) {
document.write(fbResults.cats[0].title);
});
});
</script>
</head>
<body>
</body>
</html>
And here is the data that it's reading:
{"cats":[
{"id":"1","title":"mytitle1","colour":"#EE297C"},
{"id":"2","title":"mytitle2","colour":"#EE412F"},
{"id":"3","title":"mytitle3","colour":"#F5821F"},
{"id":"4","title":"mytitle4","colour":"#00AEEF"},
{"id":"5","title":"mytitle5","colour":"#00B495"},
{"id":"6","title":"mytitle6","colour":"#006476"}
]}
It is not displaying anything on the page.
On firebug console I get this error:
The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.
No traces of the json data there
What I'm I doing whong?
You shouldn't document.write after the page has loaded (which is certainly the case here).
If you want to write it to the page, you'll need to create HTML and append it. Just replace the document.write:
$('body').append('<p>'+fbResults.cats[0].title+'</p>');
Update:
Your example makes a fully qualified URL call. Is that server the exact same one that you're running the page from? If it isn't the XHR will just eat the request (and sometime not tell you). If you need to go cross domain, you'll need to use JSONp. If you're attempting to run this locally while pulling data from the net, it'll break.
Try this
$.each(fbResults.cats,function(index,item){
document.write(item.title);
});
Working sample : http://jsfiddle.net/zWhEE/8/
its seems work for me please check this
http://jsfiddle.net/TxTCs/1/

Setting data attribute for object element in html

i have an object element in my html body to show an Active reports which exports to a .pdf file. I need to use javascript to automatically print the pdf out to the client's default printer and then save the pdf to the server:
<script language="javascript" type="text/javascript">
// <!CDATA[
function PrintPDF() {
pdf.click();
pdf.setActive();
pdf.focus();
pdf.PrintAll();
}
// ]]>
....
<body onload="return PrintPDF();">
<form id="form1" runat="server">
<object id="pdfDoc" type="application/pdf" width="100%" height="100%" data="test.aspx?PrintReport=yes&SavePDF=yes"/>
</form>
</body>
With the data hard-code in the object tag, everything run without a problem.
The problem now is that I need to pass querystring to this page dynamically. I tried to set the attribute data in the javsacript to pass the querystring. The querystring value passed successfully, but the data attribute does not seem to be set. I get a blank page.
pdf.setAttribute("data","test.aspx?PrintReport=yes&SavePDF=yes&AccNum="+AccNum);
Does anyone have a clue how I can set the data attribute dynamically to pass in querystring?
Thanks,
var pdfObj = document.getElementById('pdfDoc');
pdfObj.data="test.aspx?PrintReport=yes&SavePDF=yes&AccNum="+AccNum;
As far as the data attribute you're doing everything fine. Here are some examples:
http://jsfiddle.net/3SxRu/
I think your problem might be more to do with the order of execution. What does your actual code look like? Are you writing over the body onLoad function or something?
Also, I assume using the data attribute is a requirement. HTML5 defines data-*. This attribute isn't really valid. Again, maybe your system requires it.
I suspect that things are happening out of order. Try waiting until the onload event of the window before adding the embed.
Also, I suggest using a script like PDFObject to handle the embedding since it is a reliable way to embed PDF across all the various browsers out there. For example you might have something like the following:
<html>
<head>
<title>PDFObject example</title>
<script type="text/javascript" src="pdfobject.js"></script>
<script type="text/javascript">
window.onload = function (){
// First build the link to the PDF raw data ("bits")
// getQueryStrings assumes something like http://stackoverflow.com/questions/2907482/how-to-get-the-query-string-by-javascript
var queryStrings = getQueryStrings();
var reportNameParamValue = queryStrings["reportName"];
var pdfBitsUrl = "getReportPdfBits.aspx?reportName=" + reportNameParamValue;
// just in case PDF cannot be embedded, we'll fix the fallback link below:
var pdfFallbackLink = document.getElementById("pdfFallbackAnchor");
pdfFallbackLink.href = pdfFallbackLink;
// now perform the actual embed using PDFObject script from http://pdfobject.com
var success = new PDFObject( {
url: pdfBitsUrl;
}).embed();
};
</script>
</head>
<body>
<p>It appears you don't have Adobe Reader or PDF support in this web
browser. <a id="pdfFallbackAnchor" href="sample.pdf">Click here to download the PDF</a></p>
</body>

Categories