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
Related
There is a page like this:
<html>
<head>
...
<script type="text/javascript" src="http://someserver/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="http://someserver/getJS?key=123456" ></script>
...
</head>
...
</html>
And the content of getJS
$(document).ready(function() {
...
}
The key is dynamically generated every time the page is loaded, like a session key. The script http://someserver/getJS?key= is only accessible once for each key. On the second access, it returns NULL. However, viewing from Developer Tools in Chrome, the content of getJS is cached in the Resources/Application panel.
My questions:
Using a GreaseMonkey script or snippet, how do you access the content of any external script object as String without calling the URL again?
In Chrome's DevTools, how do you access any script (and other objects) under the Resources/Application panel in a snippet?
Not sure if I'm interpreting your question correctly, but if you're trying to do what I think you're trying to do... You can use Javascript to dynamically create a <script> element, change its src property, and append it to the DOM.
(function() {
var body = document.querySelector('body');
var externalScript = body.createElement('script');
externalScript.src = "https://host.com/script.js";
document.body.appendChild(externalScript);
})()
I have an argument in JS which holds pretty much the data. It's the server information to my server. It changes often, e.g 20/64 or 32/64. You get the point.
I am trying to get the contents of the data to go on an external site, however, when I try, it doesn't work.
To summerise, I have a div which holds the data, I want to get that data using JS and put it on an external site which isn't using the same domain or web server.
HTML FILE:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
<div id="serverstats-wrapper"></div>
<script src="import.js"></script>
</body>
JS File:
$(document).ready(function(){
$.post("query.php", {},
function (data) {
$('#serverstats-wrapper').html (data);
});
});
var the_main = document.getElementById("serverstats-wrapper");
var the_data = the_main.textContent ? the_main.textContent : the_main.innerText;
I want to get the text from the html file to the js file then take it to an external website.
Tasid! This won't work! JS does't have such a technique implementet. To do so, you need node.js. This allows you to send the data over a socket to your other webserver.
It does't work difrently, because JS is executed direct on your PC.
You can grab data from another site; but you cannot inject JS code into another site. Here are some methods to retrieve html from another site: Include another HTML file in a HTML file
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.
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>
Ok this is really frusturating me because I've done this a hundred times before, and this time it isn't working. So I know I'm doing something wrong, I just can't figure it out.
I am using the jQuery .get routine to load html from another file. I don't want to use .load() because it always replaces the children of the element I'm loading content into.
Here is my .get request:
$(document).ready(function() {
$.get('info.html', {}, function(html) {
// debug code
console.log($(html).find('ul').html());
// end debug code
});
});
The file 'info.html' is a standard xhtml file with a proper doctype, and the only thing in the body is a series of ul's that I need to access. For some reason, the find function is giving me a null value.
In firebug, the GET request is showing the proper RESPONSE text and when I run
console.log(html);
Instead of the current console.log line, I get the whole info.html as output, like I would expect.
Any ideas?
You cannot pull in an entire XHTML document. You can only handle tags that exist within the <body> of an html document. Frustrating. Strip everything from info.html that isn't within your <body> tag and try it again.
There are other potential ways around this issue - check below "Stackoverflow Related Items" at the base of this response.
From the Doc: (http://docs.jquery.com/Core/jQuery#htmlownerDocument)
"HTML string cannot contain elements that are invalid within a div, such as
html, head, body, or title elements."
Stackoverflow Related Items:
Simple jQuery ajax example not finding elements in returned HTML
What is the best practice for parsing remote content with jQuery?
I know this is an old post but I've been having the EXACT same frustrating problem for a couple of hours and have found a solution. For me what actually worked was to have the html content wrapped with a form tag.
So having the following html source:
<html>
<head>
<body>
<form>
<div id="content">Some Stuff</div>
</form>
</body>
</head>
</html>
With this jquery snippet should work:
var callback = function (data) {
alert($("#content", $(data)).html());
};
$.get(url, null, callback, null);
Hope this helps...
I have found this being pretty clean solution:
var elementInResponse = $("<div>").html(responseText).find(selector);
Wanting to do the same thing and knowing that JQuery load(..) does it, I had a look in the code. While you can't turn a complete html response directly into a JQuery object, you can append it to one so:
function(data, textStatus, xhr) {
$(target).html(jQuery("<div>").append(data).find("#snippet"));
// Create a dummy div to hold the results,
// inject the contents of the document into it,
// Locate the specified elements
}
The response from the server that goes into data is like:
<! doctype ... >
<html>
<head>
...
</head>
<body>
<div id="snippet">
<p>Some content here that we are interested in</p>
</div>
</body>
</html>
Try including whole body within a <div> tag, e.g. <body><div>content</div></body>.