Setting data attribute for object element in html - javascript

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>

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

How to read local Storage JSON in angular index.html file and show in View page source as a script

I have JSON in my localStorage which I want to read in my angular index.html file and also I want to show this JSON when I see the View page source. Below code, I have tried.
Note: When I am seeing View page source then only Plain HTML is showing noting dynamic from localStorage.
<html>
<body>
<script type="text/javascript">
window.onload = function() {
alert(JSON.stringify(JSON.parse(localStorage.getItem('profileJson'))));
var data = JSON.stringify(JSON.parse(localStorage.getItem('profileJson')))
var nameFromJson = data.default.provider.name
document.getElementById("demo").innerHTML = nameFromJson;
}
</script>
<p id="demo"></p>
<app-root></app-root>
</body>
</html>
View page source only gets the raw HTML then displays it. Therefore, you wouldn't be able to access the local storage when you're getting that text out because it would require JavaScript to be run.

How to get the content of an external <script> object without calling the src URL again?

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);
})()

set the src attribute of an iframe, then load into page, using javascript

I'm currently working on a simple google chrome extension to play youtube videos in a separate tab based on an omnibox query. For example, if a user searches for "tupac", my extension redirects to chrome-extension://{chrome-extension-id}/just-play-music.html?tupac.
Now I want to embed a youtube iframe player on this just-play-music.html page, set to play a list of videos returned by a search on the string "tupac". Following the Google API docs, this is achieved easily enough by providing the following src url for my iframe: http://www.youtube.com/embed?listType=search&list=QUERY where QUERY in this case would be replaced by "tupac".
However, here is where I've reached a sticking point. I can't figure out how to configure my .html and .js files so that this happens dynamically when the page loads, based on the url of the page. Below is the code for just-play-music.html and the .js file it is linked to.
Again, the goal here is to generate a youtube iframe with a src attribute created by grabbing location.search (I realize this is an inelegant way of doing this) when the page loads, and then insert this iframe into the content section. Please let me know if you see something very wrong, this is admittedly my first time working with javascript.
html
<html>
<head>
<link rel="stylesheet" href="main.css" type="text/css">
<script src="main.js"></script>
</head>
<body>
<section class="header">
<h1>just play music:</h1>
</section>
<section id="movie" class="content">
</section>
</body>
</html>
javascript
function iframeDidLoad() {
alert("Done");
}
function loadIframe() {
var query = location.search;
var target = "http://www.youtube.com/embed?listType=search&autoplay=1&list=" + encodeURIComponent(query);
var frame = '<iframe id="ytplayer" type="text/html" width="640" height="390" src="'+target+'" frameborder="0" />';
document.getElementById('movie').innerHTML = frame;
iframeDidLoad();
}
You should do a console.log on the location.search. It gives you a string you need to parse, e.g., "?key=value&key2=value2&etc=another+value". I think you might need to address that.
So if where it says list= needs to be just tupac, you're going to need to convert your search string from a string that looks like this: ?query=tupac to a string that looks like this tupac by doing something like:
var query = location.search.split('=')[1];
What this does is it splits the string up into two pieces, using the = sign to divide them, then using [1] to select the second piece (array indices start from 0). Then you'll have just the tupac portion of the string (or whatever the query string is for [e.g., U2]).
If your query string has multiple parameters, you needs to parse each of those first, e.g., if your query string looks like this:
?somekey=somevalue&query=tupac&someotherkey=some+other+value
you're going to need to do something like this:
var query;
location.search.split('&').forEach(function(piece) {
if (piece.indexOf('query=') !== -1)
query = piece.split('=')[1];
});

How do I set the src address dynamically?

I am trying to grab information from the page url to set the src for a data file.
So, say page url is: page.html?x=data_file_3
(The ideas is I could change the url to access other data files: data_file_4, etc.)
I grab the "data_file_3" part of the url and put it in a variable:
(the code I use for this works fine -- so result is)
folder = "/data_file_3/content.js" -- the content of this file is just an array
Then I try this:
<script id="url" type="text/javascript"></script>
<script language="javascript">
...
var u = document.getElementById('url');
u.src = folder;
...
</script>
But this doesn't work (the array data does not show up on the page). I put this code right where I used to hard code:
<script type="text/javascript" src="/data_file_3/content.js"></script>
The hard-coded version works. Any ideas about how I can do this?
Sounds like you are trying to create script tags dynamically.
var scr = document.createElement('script');
scr.src = 'script_path';
document.getElementsByTagName('head')[0].appendChild(scr);
You can wrap this in a function where 'script_path' is whatever you're path you're passing in.
Note also that 'text/javascript' is not required. All browsers understand that its javascript.

Categories