I have a Node.js application in which I have implemented CSRF. It's working fine, and when I had some JavaScript inline in a JADE file, I simply used #{token} to get the token into the JavaScript.
However, I've now moved my JavaScript into external files, and can't figure out a simple way to input the CSRF token into the code. How can I do so?
You can simply implant your token into one dom element, say, a hidden div.
And use javascript to get that element and read the token.
Consider to use a META-element in the document's head to hold the CSRF token. Then use this token in AJAX requests. If your server returns a new token, replace the contents of the META-element.
HTML:
<html>
<head>
<!-- generate this server-side -->
<meta name="csrf" content="A_VALUE">
</head>
<body>
<form>
<input type="text" name="something">
<input type="submit" value="Send">
</form>
<body>
</html>
JAVASCRIPT
(function($) {
var csrf = $("meta[name='csrf']").attr("content");
$("form").submit(function (evt) {
evt.preventDefault();
alert("CSRF: " + csrf);
});
})(jQuery);
(http://jsfiddle.net/ZmesY/1/)
Just write an inline script with a global token var which you can reference from any other scripts.
script
| window.myApp.token = #{token};
And in your js:
$.ajax({ data: { _csrf: window.myApp.token }, ...});
(The exact syntax might be wrong, was a long time since i used jade, but I'm sure you get the general idea).
Related
I am trying to load an external HTML page (common navigation) into my current HTML page. I tried the load function but it is deprecated. Can you tell me another way to include it? I am not using any server.
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#content').load(" nav.html ");
});
</script>
</head>
<body>
<div id="content "></div>
</body>
</html>
Try this
<script>
function loadPage(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
};
document.getElementById('content').innerHTML =
loadPage('your_html_file.html');
</script>
<div id="content">
</div>
Take both file pages in same directory then you can use simple button on link to use external file. for example
<button> External file </button>
Button is your choice it's just example for understanding you can simple use html link.
You should use the SSI-function.
There is several ways but this can solve your problem.
<!--#include virtual="PathToYourFile/YourFile.html" -->
This can be inserted into a <div> for further styling in CSS.
REMEMBER! Due to some limitations in html-doctypes you cannot inlude a .html-file into an .html-file. You have to use another format as .shtml where you can inlude your .html-files. You can include .html into your .shtmlfile. This was also what .shtml was originally created for.
This is because it is part of the XHTML (Dynamic XML HTML)...
To change a file
Your approach on the HTML is correct and also your JS. I include a lot of html-files containing texts there.
My approach is that when a page is loaded some text will be loaded with the <!--#include virtual="" --> inside a <div>. Below JS is used to change the content in the <div>. As Daniel Beck stated below: "...at least in Apache the server needs to be configured to check particular file extensions...".
You configure your file in your .htaccess-file. But ONLY do this if you know what you are doing.
Some (newer?) servers have a default setup of which you don't need to alter the .htaccess-file if you want to be able to include .html-files. At least you are able to include .html-files into .shtml-files.
I have included a Mimetype converter which tells the browser how it should read the file. For txt/html I have told the script that it should use the character encoding ISO-8859-1. Others as UTF-8 could also be used. This depends on your and your receivers native language.
Take into consideration to use the e.preventDefault();. With this i tells the browser NOT to see this as navigation link and will therefore only load the content in the <div>.
$(function() {
$('#ButtonsID').click(function(e) {
$('.DivClass').load('PathToFile/File.shtml');
e.preventDefault();
});
});
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
});
I want to process a GET extension in a HTML page and not a PHP page.
I have looked through the internet and not found anything.
URL = examplesite.com?id=1234
I assume this would go to the index page on the domain. As the index page is a HTML page, is there a way to get the details of the extension transferred to another link I have in the html script that emails me when someone looks at the site.
<script src="trigger.php">
</script>
This way I can customise the extension to know where the person found me. id=1234 is from twitter, id=2345 from FB etc.
Then i could place the extension onto the script to send me the email.
<script src="trigger.php?id=1234">
</script>
Is there a way to get the HTML page to process extension and pass it on in a variable of some sort.
Thanks in advance
Robert
You can do it in Javascript in the HTML. window.location.search contains the query string from the URL.
You can then use an AJAX request to send the query string to your server script.
<script>
$(document).ready(function() {
var script = 'trigger.php' + window.location.search;
$.get(script);
});
</script>
This is not possible with plain HTML. By definition, HTML is not dynamic. It can't process anything you want. However, there are three options.
Firstly, you can use JavaScript and AJAX calls to make another HTTP request to examplesite.com/processID.php (or another PHP page) which will process the request.
Another way to use JavaScript would be to use a client side API such as MailChimp to send the email directly from the users computer.
Or you could just redirect your root page for your domain examplesite.com to lead to index.php. I'm sure that's very easy to configure in mainstream servers such as Apache or Nginx. Otherwise please ask another question on Server Fault about how to set this up using your server.
If you are using a PHP hosting provider, they should also be able to help redirect the root page. If you don't have any access to PHP on your hosting provider, you're out of luck. You must only use the second option.
Do it with ajax
<form id="form1">
<input type="text" />
<button type="submit" id="sendforms">send</button>
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#sendforms").click(function() {
var combinedFormData = $("#form1").serialize();
$.get(
"trigger.php",
combinedFormData
).done(function(data) {
//alert("Successfully submitted!");
$("#result").html(data);
}).fail(function () {
//alert("Error submitting forms!");
})
});
});
</script>
I'm writing a static web site that uses JQuery to make some AJAX calls to a RESTful API and populate the page with data.
The site functions correctly (and quickly), everything is good.
As I extend the site and add additional pages, I'm noticing that I'm duplicating certain regions on every page.
For instance, each page shares a common header element.
<header>...Some non-trivial content...</header>
Rather than repeat this definition on each page is there some mechanism, by which, I can define this section once and include it in each document.
Remember that the pages must be served statically but any standard complaint browser functionality can be utilised.
Is there a good way to do this, and what is it or, will I have to abandon DRY principles for this aspect of my client side code?
There's definitely some ways to achieve this. You could either do it using some features of your server-side language that allows to include the content of a page in another page, or if you do not have any server-side technology, you could simply put that code in it's own html document and load it's content using AJAX.
In jQuery it could look like:
$('#header').load('header.html');
However, if the content isin't static for all pages, you could always define a JS module that would be responsible to render this header. You module could make use of a client-side templating engine, like Mustache, Handlebars, etc. However you do not have to use any of these.
Here's a simple example:
DEMO
//in somefile.js, please note that you should namespace your modules
var Header = {
//default config
config: {
el: '#header',
title: 'Some title'
},
init: function (config) {
var cfg = this.config = $.extend({}, this.config, config);
$(cfg.el).html('<h1>' + cfg.title + '</h1>');
}
};
$(function () {
Object.create(Header).init({
title: 'Some other title'
});
Object.create(Header).init({
el: '#header1',
title: 'Yeah'
});
});
As I mentioned in the comment, this is how I do it:
main.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Main page</title>
<sript src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$('#commonsection').load('reusablefile.htm');
// which is eqvivalent to:
//
// $.ajax({
// url: 'reusablefile.htm',
// dataType: 'html',
// success: function(data){
// $('#commonsection').html(data);
// }
// });
});
</script>
</head>
<body>
<div id="commonsection"></div>
</body>
</html>
reusablefile.html:
<script>
(function($){ //separate scope to keep everything "private" for each module
//do additional javascript if required
})(jQuery);
</script>
<p>...Some non-trivial content...</p>
You could use jQuery's ajax as to load the header file. In each file you could load the html like so:
$('#header').load('header.html');
Since you're already using AJAX calls to populate your site with data, you could do the same for the common regions.
Just store the HTML for those regions in a separate file and load it in the page with AJAX. Also, you can work with caching using the Cache-Control headers on that file so you don't reload the entire content from the server with each page load.
If you're using straight HTML, you could do it with a SSI include command or by creating a template page and including it in jQuery. Both of these links might help you
Include another HTML file in a HTML file
and
http://www.htmlgoodies.com/beyond/webmaster/article.php/3473341/SSI-The-Include-Command.htm
It looks like this in modest:
main.xhtml
<?xml version='1.0' encoding='UTF-8'?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<include>reusablePiece</include>
</head>
<body>
<reusablePiece/>
</body>
</html>
reusablePiece.xml
<header>...Some non-trivial content...</header>
Very simple would be the jQuery .clone() function.
If you have more complex content I recommend looking at Handlebars.js which is a full fledged JS templating engine.
I have a url which gives json data...
I want to hit that URL from javascript but I am getting this error :
character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature
Code :
function a(){
$.getJSON(url,function(data) { alert(data);});
}
full code :
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta>
<script language="JavaScript" type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>
function a(){
$.getJSON(url,function(data) { alert(data);});
}
</script>
</head>
<body>
<input type="text"/>
<input type="submit" value="search" onclick="a()"/>
</body>
</html>
Your code seems correct.
Are you making a fully qualified URL call?
If you are making a fully qualified URL call, make sure of the following.
You are calling the same domain(same server). You can not make a
simple JSON call to another domain.
If you want to use a cross domain call, you'll have to use JSONp
Update:
This is not working since it is a cross domain call.
Work around for this
JavaScript
Create a function
function getMyData(data) {
alert(data);
//Do the magic with your data
}
Server side
On server end wrap your data inside function syntax
getMyData("Enter your data here");
JavaScript
Then create a script tag and add a link to your cross-domain page
<script type="text/javascript"
src="cross ref url">
</script>
For reference: wikipedia
EDIT: Another option is Create a proxy on your domain. ie create a page in your domain which internally calls the cross-domain page and return the same data to your Ajax call.
I read Google Chrome Extensions Developer's Guide carefully, it told me to save options in localStorage, but how is content_scripts able to get access to these options?
Sample:
I want to write a script for a couple of domains, and this script should share some options on these domains.
content_scripts:
//Runs on several domains
(function(){
var option=getOptions();
//Get options which have been set in options.html
if(option){
doSome();
}
})
option_page:
<html>
<head>
<title>My Test Extension Options</title>
</head>
<body>
option: <input id="option" type="text" /><br />
<input id="save" type="submit" /><br />
<span id="tips">option saved</span>
<script type="text/javascript">
(function(){
var input=document.getElementById('option');
var save=document.getElementById('save');
var tips=document.getElementById('tips');
input.value=localStorage.option||'';
// Here localStorage.option is what I want content_scripts to get.
function hideTips(){
tips.style.visibility='hidden';
}
function saveHandler(){
localStorage.option=input.value||'';
tips.style.visibility='visible';
setTimeout(hideTips,1000);
}
hideTips();
save.addEventListener('click',saveHandler);
})();
</script>
</body>
</html>
I would think you could use the chrome.extensions.* API to create a line of communication to a background page that is running under your extension ID, thus giving you local storage.
I think this is possible because the Content Script docs specify that the chrome.extensions* API's are available to content scripts. But I have never tried this.
You would then just have to send messages from the background page to the content script when a connection is made. You could even send one message with all the settings in a literal object.
Here is an example of creating two way communication I wrote about earlier. You could implement this or create a custom solution but I think this is how you would achieve what you are looking for.