Save string as local file.txt - javascript

I want to save a string to a local file.txt
I have this HTML:
<div class="content"></div>
and this js
var string = 'ThisIsMyString';
var a = 'text file';
$('.content').append(a);
As you can see the text 'ThisIsMyString' from var a gets saved in the file just as i wanted but the problem is that if you inspect the element you will be able to see my text inside the anchor tag.
You can check it here.
http://jsfiddle.net/VBJ9h/2389/
The question is, is there any way hide the content of the file from the a tag?

It is not possible to hide content from the Developer Console like that.
If you want to request something without revealing an explicit link you should consider using an ajax request, and some programming language to provide a back-end for sending the file to the request.

Related

obtain url paramethers from a page called with JQuery's load() function

I have seen this question before but I haven't found a working solution.
The question is quite easy.
If I call a page like this.
div.load('page?foo=bar');
I want to be able to retrieve foo in some way an use it in a javascript called by page. But I only manage to obtain the paramethers of the parents url.
I know I can declare variables in the parents javascript code but that is not my preffered way.
So I really hope someone has a solution to this problem.
♥ you guys
You could use something like this to parse the URI:
http://blog.stevenlevithan.com/archives/parseuri
Then you can access the parameters easily from the parent page:
// Set the link that we want to load/examine
var link = 'page?foo=bar';
// Load the link content (as per your code)
div.load(link);
// Grab whatever variables we want from the link
var uri = parseUri(link);
var foo = uri.queryKey.hasOwnProperty('foo') ? uri.queryKey.foo : false;
alert(foo);
EDIT:
As bfavaretto already commented, the content loaded in via AJAX is just a string. It's not a page that will be aware of its URI.
However, if you really want the loaded content to be able to access its URI, just make it available in the content itself. For example:
$('#my_div').load('page?foo=bar)
And in the content of "page?foo=bar":
<div class="container" data-page-uri="{{ insert uri here with php, ruby, whatever }}">
<!-- my page content -->
</div>
Now in your loaded content, you can determine the URI by finding the relevant div with the "data-page-uri" data attribute. Once you have the link, you said that you know how to grab the parameters from it...
Hope that helps.
I think you have two solutions. One, if page has a hidden div, with the data needed, the second one, probably the ajax response object has the caller url. You should study the response xhr object.

How to send longer emails from a Chrome extension?

I would like to make a Chrome extension that lets users send emails with certain text automatically filled in. I was using a mailto: link, but it cannot handle strings longer than 1024 characters, and it cannot create html links. Is there a way I can fill in additional text and maybe even HTML links, from within the email page (perhaps with local storage)?
Unfortunately there is no native chrome/javascript API to my knowledge. I did some searching and found an open source option that someone was working on but it was very skeleton. He was hoping others would jump on with him and flesh it out.
Sounds like you're trying this:
For creating the URL, you can use the &body= tag and url encode the message however there is a limit to the length. It sounds like you already figured out how to open a new tag using chrome so you've been able to create shorter emails using nothing but a modified URL string. I did something similar to that on my first chrome exension. It looked something like this.
function sendToUrl(){ chrome.tabs.query({active:true, windowId: chrome.windows.WINDOW_ID_CURRENT}, function(tab) {
//while this seems to generate the URL correctly, gmail limits how long the body text can be therefore this is not a viable solution
//Also there is no javascript API therefore there is no hope of sending an email.
//Need to loop through each tab and not just the first one
var currentTab = tab[0];
var tabInformation = RPATH.getTab(currentTab.id);
var mailUrl = "https://mail.google.com/mail/?view=cm&fs=1&tf=1&su=My%20Subject&to=";
// grab the email addresss from popup.html
mailUrl += document.getElementById("to").value + "&body=";
// get formBody from popup.html
var formBody = document.getElementById("body").value;
...
//I did some other stuff that isn't relevant here
...
//Concat final mailto url
mailUrl = mailUrl + formBody;
chrome.extension.sendMessage({mailUrl: mailUrl}, function(response){ console.log(response.farewell);});
});}
For longer email bodies
That only gets you half way though. The only alternative I could think of was to split up the tab open and filling out the email body. You could modify the email body after page load completes using append. That might look something like what I have below. Notice I'm selecting the iframe element, then finding the body tag inside of there, and finally appending some html just after the tag opens. Notice the email body is nothing more then html so div, tr, br, etc tags should all work in creating a well formatted email. In my previous example I pulled the text from the form as a string. You could instead use jquery to clone the html on your popup.html page and append the cloned html. For simplicity's sake, I only put text inside the append.
$("iframe#:1t4").find("body.editable").append('<p>My long email body</p>');
I suppose from there you could run a click event but you could also leave that to the user.

Running the javascript code present on another html page through jquery

It might be a noob questions but I have just started using jquery.
My basic requirement to extract the link which is there in the javascript code present in another html (code is embedded in the html page and not in a seperate file).
The link is also present as a href attribute of <a> tag inside a tag, just to add if it is easier to extract it from there (I am using chrome so I think it considers there are no child nodes of <noscript> tag)
After this I tried doing an ajax request to the html page (using $.ajax) thinking it will run the scripts on the page but got the html code of the page in return :S . I have also heard of something called evalscripts:true but not sure if that will work here or how to use it?
I have also tried to search for the link in html code returned by my html page by using the "contains" operation of jquery.
I am doing all this to create a greasemonkey script. Please suggest
Example Code:
This is a function present inside the html of that page:
function fun() {
obj = new pollingObj('argument', "a link I want to extract comes here");
}
I want to extract the link: "a link I want to extract comes here" and then open it.on my page where I am running my jquery script
This link is also present like this on the html page:
<noscript>
blabla
</noscript>
Also is it possible to run the javascripts present on that page if the link extraction is not possible?
If you're able to get the html code of the page successfully via .ajax, and the data you want is in the HTML code, it's not worth the effort to bother with trying to run the scripts. Just access the URL through the DOM:
// ajax success function
success: function(html) {
var anchorCode = $(html)
// this assumes that noscript is a top-level element
// otherwise, use .find('noscript')
.filter('noscript')
.text(); // get the code for the anchor tag, as a string
var myLink = $(anchorCode).attr('href');
// do something with myLink
}
Edit: It turns out that jQuery is a little funny in the way it deals with noscript tags - inner tags don't appear to be considered part of the DOM, so you need to grab the text content of the tag and then use jQuery to DOM-ify it. See updated code above.

See if certain text is in URL and if so print something dynamically via javascript

Here is what I would like to ideally do within my HTML - I would like to insert a bit of javascript that checks to see if a certain directory name is listed in the current user's URL and if so, output copy on the page. For example:
If the current URL has the word "trigger" in it such as:
http://www.mysite.com/pages/trigger/dosomestuff.html
then I want to output "confirmed" on the page.
I am not too familiar with javascript, so I am hoping that someone can help!
Thanks!
if (location.href.match("trigger"))
{
document.write("<h1>confirmed!</h1>")
}

Getting content of a script file using Javascript

I have the following script element in my web page:
<script src="default.js" type="text/javascript"></script>
Using JavaScript, I want to be able to retrieve the content of the script file. I know I could use an ajax request to get the data but then I am getting something from the server that I already have locally.
So what I would prefer to do is retrieve the content from the DOM (if that's possible) or something that has the same result.
Cheers
Anthony
UPDATE
I was trying to simplify the question, maybe a bad a idea, I thought this way would cause less questions.
The real situation I have is as follows, I actually have
<script type="text/html" class="jq-ItemTemplate_Approval">
...
html template that is going to be consumed by jQuery and jTemplate
...
</script>
Now this works fine but it means each time the page loads I have to send down the template as part of the HTML of the main page. So my plan was to do the following:
<script src="template.html" type="text/html"></script>
This would mean that the browser would cache the content of template.html and I would not have to send it down each time. But to do this I need to be able to get the content from the file.
Also in this case, as far as I know, requesting the content via ajax isn't going to help all that much because it has to go back to the server to get the content anyway.
If I understand you correctly, you don't want to use Ajax to load an html template text, but rather have it loaded with the rest of the page. If you control the server side, you can always include the template text in an invisible div tag that you then reference from Javascript:
<div id="template" style="display:none;">
...template text...
</div>
<script>
// pops up the template text.
alert(document.getElementById("template").innerHTML);
</script>
If you are just looking for to load the template so that you can have it cached, you can put the contents in a variable like this:
<script>
var template = "template text..";
</script>
or you can load it using ajax and store the template in a variable so it is accessible. It's pretty trivial in jquery:
var template;
$.get("template.html", function(data){
template = data;
});
unless you load a script as literal text in the page, it does not exist as text. It is interpreted by the browser and melded into the runtime, with any other scripts.
If you want the source you have to fetch it again,if with Ajax get the responseText.
It will come from the browser cache, and doesn't have to be downloaded again.
I think what you want to do is to assign a variable inside template.js. Then you have the variable available for use wherever you want in jquery. Something like:
var tpl = "<div> ... </div>"
Wouldn't this be a simpler solution to your problem? We do this in Ext JS. I think this will work for you in jQuery.
You could get the attribute of the src of the script and then use XHR to get the contents of the JS file. It's a much cleaner way of doing it IMO. e.g.:-
if(window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.status == 200 && xhr.readyState == 4) {
var sourceCode = xhr.responseText;
alert('The source code is:-\n'+sourceCode);
}
}
xhr.open("GET",document.getElementById('scriptID').src,true);
xhr.send(null);
}
Using an iFrame & HTML5 Local Storage
Save the templates for rendering later...
not stoked about the iFrame, but it seems to be working pretty good (haven't ran performance tests yet)
Put the iFrame on the page you want the template on (index.html)
<html>
<head>
<iframe src="mustache.Users.html" onload="this.remove();" class="hidden" id="users_template"></iframe>
</head>
</html>
Make sure the src attribute is set
hide the element until you can get rid of it after it loads
Put this body wrapper around your template (mustache.Users.html)
(don't worry it won't show up in the template)
<body onload="localStorage.setItem('users_template',this.document.body.innerHTML);">
<ul class="list-group" id="users" >
{{#users}}<li>{{name}}</li>{{/users}}
</ul>
</body>
replace 'users_template' with whatever name for your variable
the 'onload' attribute saves the template into localStorage during load
Now You can access your templates from anywhere
localStorage.getItem('users_template')
OR
window.localStorage.getItem('users_template')
What is in the JavaScript file? If it's actual code, you can run functions and reference variables in there just like you had cut and paste them into the webpage. You'll want to put the include line above any script blocks that reference it.
Is this what your looking to accomplish?
Why not use Ajax (well Ajah because its html :-))?
when the server is set up correctly and no no-cache or past expires headers are sent, the browser will cache it.
The way that most JavaScript import files work is they include a script, that immediately calls a function with a parameter of certain text, or of another function. To better illustrate, say you have your main index.html file, set it up like this:
<html>
<head>
</head>
<body>
<script>
let modules = {};
function started(moduleName, srcTxt) {
modules[moduleName] = (srcTxt) //or something similar
}
</script>
<!--now you can include other script tags, and any script tags that will be included, their source can be gotten (if set up right, see later)-->
<script src="someOtherFile.js"></script>
</body>
</html>
now make that other file, someOtherFile.js, and right away when its loaded, simply call that "started" function which should already be declared in the scope, and when thats done, then whatever text is passed, from the file, is stored in the main index.html file. You can even stringify an entire function and put it in, for example:
started("superModule", (function() {
/*
<?myCustomTemplateLanguage
<div>
{something}Entire Javascript / html template file goes here!!{/something}
</div>
?>
*/
}).toString());
now you can access the inner content of the function, and get all the text in between the comments, or better yet, then do other parsing etc, or make some other kind of parsing identifiers at the beginning and end of the comments, as shown above, and get all text in between those

Categories

Resources