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.
It's 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 onl oad 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.
CodePudding user response:
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>
CodePudding user response:
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