Implementing FileSaver.js saveAs() function into HTML script - javascript

Right now I am attempting to save information from an HTML page that I am creating to a text document, using javascript and the FileSaver.js package. I am not very well versed in HTML and am completely new to javascript, so odds are that I am making some egregious mistake. At the moment, I have eligrey's FileSaver.js file in the same directory as the HTML file that I am working from, so I should be able to call it simply as "FileSaver.js" in HTML.
Right now I am working from something like this:
//some irrelevant text
<script src="FileSaver.js">
function download(){
//alert("hello world");
//this alert line was to test the function call
//the alert actually appears when the <script> tag
// has no src field labeled. Just an observation.
var blob = new Blob(["Hello World"],{type:"text/plain;charset=utf-8"});
saveAs(blob,"helloworld.txt");
}
</script>
//some more irrelevant text
<input type="button" value="download" onclick="download();"/>
/*from this button I want to gather information from input text fields on the page.
I already know how to do that, the problem is creating and, subsequently,
downloading the text file I am trying to create. For simplicity's sake, the text I am
capturing in this example is hardcoded as "hello world"*/
//last of irrelevant text
//oh, and don't try to run this snippet :P
I also have eligrey's Blob.js file available in my immediate working directory as well, just in case.
As of now, the button does nothing. I am fairly sure that I am calling the function correctly considering I could receive the javascript alert text, at least when the script tag had no src. If I do add a src, absolutely nothing happens. The browser that I am testing from is the latest Google Chrome stable build (43.0 I think) on Windows XP. Please inform me of anything that I am missing and/or doing wrong. Thanks in advance

You cannot have a script tag with a src attribute and content inside the tag. Split it into two separate script tags. See What if script tag has both "src" and inline script?
Note that <script> cannot be a self-closing tag
<script src="FileSaver.js"></script>
<script>
function download(){
//alert("hello world");
//this alert line was to test the function call
//the alert actually appears when the <script> tag
// has no src field labeled. Just an observation.
var blob = new Blob(["Hello World"],{type:"text/plain;charset=utf-8"});
saveAs(blob,"helloworld.txt");
}
</script>

Related

HTML File Not Recognizing Functions Defined in external linked js file?

I am just starting to learn some programming for the first time and had a question I was hoping someone could help with, hopefully nothing too obvious I am missing.
(Revised Explanation Including Code Samples)
I am using a button to change the inner-html of an element, but I am trying to do the same thing in three ways. For the first way, I can do it. For the second two, I am having trouble and was looking for guidance:
First way I am doing is changing the innerhtml of a paragraph element, by clicking a button that has a statement defined directly behind the onclick event attribute for the button. This is working, code I use can be seen below:
<p id="change1">Does the button below change my text when I click it, based on entering a js function directly behind an onclick event entered as a button attribute?</p>
<button type="button" onclick="document.getElementById('change1').innerHTML = 'Yes_1'">See If It Works_1</button>
Second way I am trying to do this is by using a button that calls a function I defined within a script tag in my html file. The function I defined is supposed to perform the task of changing the innerhtml of the paragraph element I defined. This is not working, code sample can be seen below:
<p id="change2">Does the button below change my text when I click it, based on calling A Function Defined in script tag within My HTML File on with an onclick event?</p>
<button type="button" onclick="internalfunction()">See If It Works_2</button>
<script>
function internalfunction() {
document.getElementById("change2").innterHTML = "Yes_2";
}
</script>
Third way I am trying to do this is the same as the second way, only instead of calling a function defined within a script tag in my HTML file, I am calling one I defined in an external js file. This file however sits in the same directory as my HTML file on my computer. This was is also not working right now. Sample of my code, and the way I linked to the js file can be seen below:
Here is the code in my HTML file:
<p id="change3">Does This Button That Calls A Function Defined in My External JS File Work?</p>
<button onclick="externalfunction">See If It Works_3</button>
here is the function I want to call in my external js file:
function externalfunction(){document.getElementById("change3").innerHTML="Yes_3"};
here is the way I linked to my js file, entering this within the head of the html file:
<script src="javascript.js"></script>
Per some help on the help on the comments and some more review this was confirmed a typo issue where () were omitted to call a function and innerHTML had been misspelled.

Not getting tags html in page source

I have multilingual single page html application where I set html of tags by calling function on document.ready. However I am not getting html of any tag in page source when I view page on View Page Source. How can I get the tags in page source? document.ready is in the last script tag of the page.
$(document).ready(function() {
var lang = // get the language.
translateFunction(lang);
});
Below function is in js file. This file is added above the last script tag (i.e. document.ready script).
function translateFunction(lang) {
$("[tkey]").each(function (index)
{
var strTr = lang_resource[lang][$(this).attr('tkey')];
$(this).html(strTr);
});
}
<h1 tkey="firstH1"></h1>
Language wise data is in json format in the same js file with translate function.
When I view the page source, I see only
<h1 tkey="firstH1"></h1>
Where it needs to be like below,
<h1 tkey="firstH1">Anything from the translate function.</h1>
On the page, you can see the desired output, but in the page source, I am not getting html set. What I want to do is, I want set html of the tags in javascript on document.ready. How to do it?
EDIT
We want to add meta tags. And set keywords and description language wise. This is the main concern. The keywords and description are set in translate function. Will the crawler take the keywords and description?
We have two links language wise in site map. So when user select say french language, it will redirect to www.mysite.com?lang=fr and all the tags are set in french language. So the meta keywords and description.
Firstly if this is the exact code,
$(document).ready(function() {
var lang = // get the language.
translateFunction(lang);
});
there is error in itself...
there should be some value for var lang

Can't append script element to head

Current variant looks like that (I tried solution offered here: Can't append <script> element):
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head").append(s);
Previous variant was:
$("head").append($('<script type="text/javascript" src="js/properties.js"></script>'));
And both of them don't work. "properties.js" is also in "js" folder, but if I remove this part of path, it doesn't change anything.
I also tried to use ' instead " and check addBlock: I had it installed, but it's disabled on this page.
Changing "append" function to "appendChild" also didn't help.
"properties.js" contains just one line:
var PREFIX_URL = "http://localhost:8080/app-rest-1.0.0-SNAPSHOT";
And firstly I declare it in "main.js" to which I, in fact, try to connect this file.
Explain, please, what I'm doing wrong.
Add all your <script> tags right before the closing </body> tag, because when the browser encounters a <script> tag it begins downloading it and stops rendering of the page. So by placing them at the bottom of the page you make sure your page is fully loaded before trying to interact with the DOM elements. Also $("head") returns an array of all the <head> tags. You should also enclose your calls in a $(document).ready() function.
<!-- Your html tags here -->
<script type="text/javascript">
$(document).ready(function(){
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head")[0].append(s);
});
</script>
</body>
I made JSBin example. You can see in console that last script tag is the one you need. So the your code is correct.
If your IDE don't highlight 'var' - it may be error not in javascript. You can place it in a wrong place for example.
Can you provide link to a gist (or pastie.org or smth) for us to better understand your problem.
P.S. The code $("head")[0].append gives me undefined ( note to previous answer)

Print Javascript in Javascript?

I am in the process of making an addon for a software that basically allows you to have 'responsive' adverts, by checking the page size with javascript and then outputting the relevant ad code to the screen.
This works fine for text ad codes, however I've hit a snag when the ad code is javascript - I can't get the user-provided javascript to output to the page and be executed.
Is this possible at all?
Here is some example code:
<div id="admanagerresponsive">
<script type="text/javascript">
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;
if (adWidth >= 728) {
<output ad code>
}
</script>
</div>
The code above will be directly in the page.
Is such a thing possible?
EDIT:
could be any advertiser's code, such as adsense. It'll be user provided, and will be standard html. However, it could contain tags, and these will need to be rendered and outputted correctly...
If you really need to inject add html code containing script tags and you are award of the security problems, i suggest to use a library like jQuery that takes care about the cross browser issues with executing <script> tags added later.
Additionally you need to take care about various pitfalls like:
Html paring is done before script parsing, so no matter where a </script> appears this will immediately end your script.
The examples are important for the situations where you have that code as inline script inside your html page.
Example 1:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
// if you add </script> <b>this is visible as html</b> and everything below is not script anymore
}
</script>
Example 2:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
var string = "<script> var test;</script>";//the same problem here everything behind the closing script tag is html and not script anymore
}
</script>
So if you need to have some script to inject there you need to make the </script> not to be detectable by the html parser:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
var string = "<script> var test;</sc"+"ript>";//that way the html parser does not detect the closing script tag
}
</script>
A better solution is not to use inline script at all, not only for that reason, but because you should always keep css, js and html separated.
Break it into two ideas. From your HTML above, just call a js function you wrote somewhere else. Initially have that js function be an alert, to verify that works.
Once that works, you have the problem: how can I get custom js for a page? The answer to that is hopefully that you can create and load a (one-off, custom) js file the same way you create an html file. Or, libraries such as now.js could help. Or, there is a script portion of your html page that you understand how to assemble to include the js.
You could even preload all your size possibilities, then have the js routine from the first paragraph pick the right routine to call,

how to re-factor/extract methods to separate file for re-use

I'm fairly new to the whole JQuery/javascript world, but I've managed to wack together a working jqgrid with a datepicker & custom control (used jquery auto complete) based on code samples i found on the net. I've added the code to a T4 template in my project as it'll probably act as a base/starting point for most pages. (Side note. I'm using asp.net MVC)
JFIDDLE: LINK
1.) I'd like to move the initDateEdit & initDateSearch to the same function (using a parameter, to disable/enable the showOn property) as they are basically similar.
2.) How would be the best way to set nonWorkingDates from outside the new function/file. same applies to the autocomplete_element (I'd like to specify the url)
Changing
"function nonWorkingDates(date)" to => "function nonWorkingDates(date, nonWorkingDates)"
isn't working, (guess it's got got something to do with how its gets called "beforeShowDay: nonWorkingDates")
Thanks in advance!
If you have a chunk of JS code like this:
<script type="text/javascript">
... code goes here ...
</script>
You simply copy the whole thing, eliminate the containing script tags, and save the raw code
... code goes here ...
to a file, which you then include with:
<script type="text/javascript" src="yourfile.js"></script>
However, since you're using jquery, you'll have to make sure that this above snippet is placed AFTER the script tag that loads up jquery, or you'll get a "no such function" syntax error.

Categories