Why is this alert box not popping up when button clicked? - javascript

I've been writing a script to check for reflective XSS vulnerabilities. So far, it has an input for a URL with * in place of queries and an error checker for malformed URLs. It also has a file uploader for users to upload "payloads". However, I recently made a part that replaces * with the contents of the payload, and then for debugging purposes, I made it alert() the variable with the file contents. However, its not working. Here's my code:
function selectPayload(y) {
var fr = new FileReader();
fr.readAsText(document.getElementById('file').files[0]);
fr.onload = function() {
var dir = fr.result;
var payload = y.replace("*", fr.result);
alert(payload);
};
}
function myFunction() {
var errors = [];
var x = document.getElementById("myText").value;
if (!x.includes("http://") && !x.includes("https://")) {
errors.push('missing HTTP or HTTPS in URL');
}
if (!x.includes("*")) {
errors.push('missing * in place of query')
}
// Renders errors
if (errors.length) {
x = 'Error: ' + errors.join(', ') + '!';
}
document.getElementById("demo").innerHTML = x;
selectPayload(x);
}
<!DOCTYPE html>
<html>
<head>
<title>Slingshot.XSS</title>
</head>
<body style="font-family:monospace;" align="center">
<h2>Slingshot.XSS</h2>
<h3>Slingshot.XSS is a script that launches pre-loaded XSS payloads at a target to test its vulnerabilities.</h3>
<h4>Please report all issues to
or contact me at email#example.com.</h4>
Source Code / Learn More
<br />
<h4>Enter a URL with <b>*</b> in the place of query.</h4>
<h5>Example: <code>https://www.google.com/#q=*</code></h5>
<input type="text" id="myText" placeholder="Enter a URL"> <button onclick="myFunction()">Submit</button>
<p id="demo">No Submitted URL</p>
<h4>Select a payload:</h4>
<h5>Default payloads in <code>payloads</code></h5>
<input type="file" id="file"> <button onclick="selectPayload()">Submit</button>
</body>
</html>
What am I doing wrong?

You have the second button calling the wrong function. Changed to call myFunction() instead of selectPayload(). Unless you intended to call selectPayload() with the second button, in which case you neet to pass it an argument like it expects.
function selectPayload(y) {
var fr = new FileReader();
fr.readAsText(document.getElementById('file').files[0]);
fr.onload = function() {
var dir = fr.result;
var payload = y.replace("*", fr.result);
alert(payload);
};
}
function myFunction() {
var errors = [];
var x = document.getElementById("myText").value;
if (!x.includes("http://") && !x.includes("https://")) {
errors.push('missing HTTP or HTTPS in URL');
}
if (!x.includes("*")) {
errors.push('missing * in place of query')
}
// Renders errors
if (errors.length) {
x = 'Error: ' + errors.join(', ') + '!';
}
document.getElementById("demo").innerHTML = x;
selectPayload(x);
}
<!DOCTYPE html>
<html>
<head>
<title>Slingshot.XSS</title>
</head>
<body style="font-family:monospace;" align="center">
<h2>Slingshot.XSS</h2>
<h3>Slingshot.XSS is a script that launches pre-loaded XSS payloads at a target to test its vulnerabilities.</h3>
<h4>Please report all issues to
or contact me at keeganjkuhn#gmail.com.</h4>
Source Code / Learn More
<br />
<h4>Enter a URL with <b>*</b> in the place of query.</h4>
<h5>Example: <code>https://www.google.com/#q=*</code></h5>
<input type="text" id="myText" placeholder="Enter a URL"> <button onclick="myFunction()">Submit</button>
<p id="demo">No Submitted URL</p>
<h4>Select a payload:</h4>
<h5>Default payloads in <code>payloads</code></h5>
<input type="file" id="file"> <button onclick="myFunction()">Submit</button>
</body>
</html>

Here: I've found code that will work:
<!DOCTYPE html>
<html>
<head>
<title>Slingshot.XSS</title>
</head>
<body style="font-family:monospace;" align="center">
<script>
function selectPayload() {
var x = document.getElementById("myText").value;
var fr = new FileReader();
fr.readAsText(document.getElementById('file').files[0]);
fr.onload = function() {
var dir = fr.result;
var payload = x.replace("*", fr.result);
alert(payload);
};
}
function myFunction() {
var errors = [];
var x = document.getElementById("myText").value;
if (!x.includes("http://") && !x.includes("https://")) {
errors.push('missing HTTP or HTTPS in URL');
}
if (!x.includes("*")) {
errors.push('missing * in place of query')
}
// Renders errors
if (errors.length) {
x = 'Error: ' + errors.join(', ') + '!';
}
document.getElementById("demo").innerHTML = x;
}
</script>
<h2>Slingshot.XSS</h2>
<h3>Slingshot.XSS is a script that launches pre-loaded XSS payloads at a target to test its vulnerabilities.</h3>
<h4>Please report all issues to
or contact me at keeganjkuhn#gmail.com.</h4>
Source Code / Learn More
<br />
<h4>Enter a URL with <b>*</b> in the place of query.</h4>
<h5>Example: <code>https://www.google.com/#q=*</code></h5>
<input type="text" id="myText" placeholder="Enter a URL"> <button onclick="myFunction()">Submit</button>
<p id="demo">No Submitted URL</p>
<h4>Select a payload:</h4>
<h5>Default payloads in <code>payloads</code></h5>
<input type="file" id="file"> <button onclick="selectPayload()">Submit</button>
</body>
</html>

Related

Using JavaScript , how do I keep user input on page after it has reloaded?

I used HTML and JavaScript to allow a user to enter text and then push submit. When the user pushes submit, his text is displayed on the page. The problem is that when the page is reloaded, the text goes away. Obviously. Here is the code I have:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<p id="printhere"></p>
<TEXTAREA Name="content" ROWS="5" COLS="20" id = "userInput"></TEXTAREA>
<button onclick="display()">post</button>
<script>function display(){
var post = document.getElementById("userInput").value;
document.getElementById("printhere").innerHTML = post;
}</script>
</body>
</html>
With JavaScript, is there anyway to make input stay once the page reloads?
<p id="printhere"></p>
<TEXTAREA Name="content" ROWS="5" COLS="20" id="userInput"></TEXTAREA>
<button onclick="display()">post</button>
<script>
function display(){
var post = document.getElementById("userInput").value;
localStorage.setItem('userInputValue',post);
}
window.addEventListener('load',()=>{
var savedUserData = localStorage.getItem('userInputValue');
document.getElementById("printhere").innerHTML = savedUserData;
});
</script>
Edit for multiple input:
<p id="printhere"></p>
<TEXTAREA Name="content" ROWS="5" COLS="20" id="userInput"></TEXTAREA>
<button onclick="display()">post</button>
<script>
var num = 0;
function display(){
var post = document.getElementById("userInput").value;
localStorage.setItem(num,post);
var savedUserData = localStorage.getItem(num);
document.getElementById("printhere").innerHTML += savedUserData+'<br>';
num++;
}
window.addEventListener('load',()=>{
if (localStorage.length !== null) {
for(var i = 0; i < localStorage.length; i++){
var savedUserData = localStorage.getItem(i);
document.getElementById("printhere").innerHTML += savedUserData+'<br>';
}
}
});
</script>
You can use storage APIs (sessionStorage, localStorage) to acheive the same.
Note: Store only the data which is not sensitive. Never use it for sensitive data.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API
Example using sessionStorage: https://codepen.io/kishin-karra/pen/zYvgQZZ?editors=1010
sample code:
var savedPost = sessionStorage.getItem('text');
document.getElementById("printhere").innerHTML = savedPost;
document.getElementById("userInput").value = savedPost;
function display() {
var post = document.getElementById("userInput").value;
document.getElementById("printhere").innerHTML = post;
sessionStorage.setItem('text', post);
}
Enter the text, click post and refresh
Well, ideally this value should come from the server through an API.
However, if you're keen on doing it with JavaScript, you may consider localstorage
var post = document.getElementById("userInput").value;
localStorage.setItem("post", post);
document.getElementById("printhere").innerHTML = post || localStorage.getItem("post");
I think you can use preventDefault like this:
function display(event){
event.preventDefault()
var post = document.getElementById("userInput").value;
document.getElementById("printhere").innerHTML = post;
}

Calling Image File on Google App Scripts to Upload into GoogleDrive

I am trying to set up a way to upload image files into a google drive. It will create a folder using a timeid and place the image inside the folder it created. I am having trouble calling out the image file. This is how I am attempting this, the folder gets created but no image.
Please ignore any missing var for the timeid variable. This is working fine.
Error given:
ReferenceError: imgInp is not defined
Thank you in advance for your help!
Code.gs
var day = d.getDate();
var month = d.getUTCMonth();
var hour = d.getHours();
var minutes = d.getMinutes();
var realmonth = month+1;
var timeid = String(year)+"-"+String(realmonth)+"-"+String(day)+"-"+String(hour)+"-"+String(minutes);
var foldername=timeid;
var parentFolder=DriveApp.getFolderById("##############");
function upload(){
var newFolder=parentFolder.createFolder(timeid);
var folderidlookup = newFolder.getId();
var destination = DriveApp.getFolderById(folderidlookup);
var imgf = imgInp;
var contentType = 'image/jpeg';
var imgf = imgf.getAs(contentType);
destination.createFile(imgf)
}
Html
<form>
<div class="file-field input-field">
<div class="waves-effect waves-light btn" id="wholebtn"><i class="material-icons right">cloud</i>Browse
<input type="file" name="imgInp" id="imgInp" onchange="loadFile(event)">
</div>
<div class="file-path-wrapper">
<input type="text" class="file-path">
</div>
</div>
</form>
<button class="btn waves-effect waves-light" type="submit" name="action" id ="button">Submit
<i class="material-icons right">send</i>
</button>
JS
<script>
document.getElementById("button").addEventListener("click",upload);
function upload(){
google.script.run.upload();
}
</script>
The error you're getting is because you're trying to use a imgInp variable which you don't have it defined in any part of the code. You can get the blob file from the input, convert it to a binary array string, pass it to the server-side and finally use it to create your blob and the given Drive file, for this I used the code from this answer.
Using the examples for how to work with forms and success and failure handlers from the HTML Service guide, I put together the below code which worked successfully uploading the given image:
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
<div class="file-field input-field">
<div class="waves-effect waves-light btn" id="wholebtn"><i class="material-icons right">cloud</i>Browse
<input type="file" name="imgInp" id="imgInp">
</div>
<div class="file-path-wrapper">
<input type="text" class="file-path">
</div>
</div>
<button class="btn waves-effect waves-light" name="action" id="button">Submit
<i class="material-icons right">send</i>
</button>
</form>
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
// Add event listeners
window.addEventListener('load', preventFormSubmit);
document.getElementById("button").addEventListener("click", upload);
// Handler function
function logger(e) {
console.log(e)
}
async function upload() {
// Get all the file data
let file = document.querySelector('input[type=file]').files[0];
// Get binary content, we have to wait because it returns a promise
let fileBuffer = await file.arrayBuffer();
// Get the file content as binary and then convert it to string
const data = (new Uint8Array(fileBuffer)).toString();
// Pass the binary array string to uploadG funciton on code.gs
google.script.run.withFailureHandler(logger).withSuccessHandler(logger).uploadG(data);
}
</script>
</body>
</html>
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function uploadG(imgInp){
var parentFolder=DriveApp.getFolderById("[FOLER-ID]");
var newFolder = parentFolder.createFolder('test webApp');
var folderidlookup = newFolder.getId();
var destination = DriveApp.getFolderById(folderidlookup);
var contentType = 'image/jpeg';
// Convert the binary array string to array and use it to create the Blob
var blob = Utilities.newBlob(JSON.parse("[" + imgInp + "]"), contentType);
blob = blob.getAs(contentType);
destination.createFile(blob)
return 'Filed uploaded!';
}
File Upload Dialog
Run upLoadMyDialog() from script editor to get it started. The select file and click upload.
function fileUpload(obj) {
var d=new Date();
var ts=Utilities.formatDate(d, Session.getScriptTimeZone(), "yyyy-MM-dd-HH-mm");
var folder=DriveApp.getFolderById("****** Enter FolderId *******");
var file=folder.createFile(obj.file1).setName(ts);
}
function uploadMyDialog() {
var ss=SpreadsheetApp.getActive();
var html='<form><input type="file" name="file1"/><br /><input type="button" value="Upload" onClick="google.script.run.fileUpload(this.parentNode);" /></form>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");
}
With eventListener:
function uploadMyDialog() {
var ss=SpreadsheetApp.getActive();
var html='<form id="f1"><input type="file" name="file1"/><br /><input type="button" value="Upload" id="btn1" /></form>';
html+='<script>window.onload=function(){document.getElementById("btn1").addEventListener("click",function(){google.script.run.fileUpload(document.getElementById("f1"))})}</script>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");
}

Add url as parameter for query using Tesseract OCR

I am using tesseract ocr and it is working perfectly. But my question is can I run tesseract with a url as parameter.
I am looking to do the following
localhost/test.html/?othersite.com/image/image2.jpg
Some Image url for demo:
1. https://i.imgur.com/leBXjxq.png
2. https://i.imgur.com/7u9LyF6.png
when the results are processed it would then come to a text-area box.
Here's a code :
<html>
<head>
<title>Tesseract-JS Demo</title>
</head>
<body>
<input type="text" id="url" placeholder="Image URL" />
<!--<div id="ocr_results"> </div>-->
<div id="ocr_status"> </div>
<div>
<label>Filed1
<label>
<textarea id="txt" ></textarea>
</div>
</body>
<script src='https://cdn.rawgit.com/naptha/tesseract.js
/1.0.10/dist/tesseract.js'></script>
<script
src="https://cdnjs.cloudflare.com/ajax/
libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function runOCR(url) {
Tesseract.recognize(url)
.then(function(result) {
document.getElementById("txt")
.innerHTML = result.text;
document.getElementById('txt').focus();
}).progress(function(result) {
document.getElementById("ocr_status")
.innerText = result["status"] + " (" +
(result["progress"] * 100) + "%)";
});
}
document.getElementById("url")
.addEventListener("change", function(e) {
var url = document.getElementById("url").value;
runOCR(url);
});
</script>
You can do localhost/test.html?image=https://i.imgur.com/leBXjxq.png
And you can get the image from the URL in JavaScript like so:
const urlParams = new URLSearchParams(window.location.search);
const myImage = urlParams.get('image');
myImage variable will be: "https://i.imgur.com/leBXjxq.png" and then you can pass it to your OCR method.
A sample code will be:
const urlParams = new URLSearchParams(window.location.search);
const myImage = urlParams.get('image');
if (myImage) {
runOCR(myImage);
}
Here is a link with updated code: https://gist.github.com/kolarski/0bc2a3feb02adb1b63016d0d78b3653c

how to create webservice and upload my xml file into my webservice with ajax

i have created a button in html page and read a xml file , i want to upload this file into the webservice and how to create a webservice with ajax method and upload and call this file in the ajax.
i have trying something
my code is:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="data.js" type="text/javascript"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
</head>
<body >
<div>
<form class="form-horizontal well">
<fieldset>
<label for="XMLFileInput"> <strong>XML</strong>
</label>
<input type="file" id="XMLFileInput" onchange="handleFiles(this.files)"
accept=".XML">
</div>
</fieldset>
</form>
<div id="output">
</div>
</div>
<br>
<br>
<footer>
<input id="getFile" type="file"/><br />
<input id="displayName" type="text" value="Enter a unique name" /><br />
<input id="addFileButton" type="button" value="Upload" onclick="uploadFile()"/>
</footer>
<script type="text/javascript" src="js/read-csv.js"></script>
</body>
</html>
and my JavaScript code is:
function handleFiles(files) {
// Check for the various File API support.
if (window.FileReader) {
// FileReader are supported.
getAsText(files[0]);
} else {
alert('FileReader are not supported in this browser.');
}
}
function getAsText(fileToRead) {
var reader = new FileReader();
// Handle errors load
reader.onload = loadHandler;
reader.onerror = errorHandler;
// Read file into memory as UTF-8
reader.readAsText(fileToRead);
}
function loadHandler(event) {
var xml = event.target.result;
processData(xml);
}
function processData(xml) {
var allTextLines = xml.split(/\r\n|\n/);
var lines = [];
while (allTextLines.length) {
lines.push(allTextLines.shift().split(','));
}
console.log(lines);
drawOutput(lines);
}
function errorHandler(evt) {
if(evt.target.error.name == "NotReadableError") {
alert("Canno't read file !");
}
}
function drawOutput(lines){
//Clear previous data
alert("hi bagish");
document.getElementById("output").innerHTML = "";
var table = document.createElement("table");
for (var i = 0; i < lines.length; i++) {
var row = table.insertRow(-1);
for (var j = 0; j < lines[i].length; j++) {
var firstNameCell = row.insertCell(-1);
firstNameCell.appendChild(document.createTextNode(lines[i][j]));
}
}
document.getElementById("output").appendChild(table);
}

Why does this error occur when it shouldn't?

I've been writing a script that will check for reflective XSS vulnerabilities. I'm having an error on a part that checks if you have "http://" or "https://" in your URL and '*' in the place of queries. However, when I put https://google.com/#q=*", it results inERROR! MISSING 'http://', OR 'https://'!`. Here's my code:
<!DOCTYPE html>
<html>
<head>
<title>Slingshot.XSS</title>
</head>
<body style="font-family:monospace;" align="center">
<h2>Slingshot.XSS</h2>
<h3>Slingshot.XSS is a script that launches pre-loaded XSS payloads at a target to test its vulnerabilities.</h3>
<h4>Please report all issues to or contact me at keeganjkuhn#gmail.com.</h4>
Source Code / Learn More
<br />
<h4>Enter a URL with <b>*</b> in the place of query.</h4>
<h5>Example: https://www.google.com/#q=*</h5>
<input type="text" id="myText" placeholder="Enter a URL"> <button onclick="myFunction()">Submit</button>
<p id="demo">No Submitted URL</p>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
// Error check
if ( !x.includes("*") && ( !x.includes("http://") || !x.includes("https://") ) ) {
document.getElementById("demo").innerHTML = "ERROR! MISSING \'*\' IN PLACE OF QUERY, \'http://\', AND \'https://\'!";
x = false;
return 0;
}
if ( !x.includes("*") ) {
document.getElementById("demo").innerHTML = "ERROR! MISSING \'*\' IN PLACE OF QUERY!";
x = false;
return 0;
}
if ( !x.includes("http://") || !x.includes("https://") ) {
document.getElementById("demo").innerHTML = "ERROR! MISSING \'http://\', OR \'https://\'!";
x = false;
return 0;
}
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
What am I doing wrong?
You check if http is not in OR https is not in. One of both will always be true.
Perform the checks one after another... for example
I've refactored your function to show how you can reduce the complexity of the code when you separate the validation logic from the rendering of the errors.
function myFunction() {
var errors = [];
var x = document.getElementById("myText").value;
if (!x.includes("http://") && !x.includes("https://")) {
errors.push('missing HTTP or HTTPS');
}
if (!x.includes("*")) {
errors.push('missing * in place of query')
}
// render the errors
if (errors.length) {
x = 'Error: ' + errors.join(', ') + '!';
}
document.getElementById("demo").innerHTML = x;
}
<!DOCTYPE html>
<html>
<head>
<title>Slingshot.XSS</title>
</head>
<body style="font-family:monospace;" align="center">
<h2>Slingshot.XSS</h2>
<h3>Slingshot.XSS is a script that launches pre-loaded XSS payloads at a target to test its vulnerabilities.</h3>
<h4>Please report all issues to or contact me at keeganjkuhn#gmail.com.</h4>
Source Code / Learn More
<br />
<h4>Enter a URL with <b>*</b> in the place of query.</h4>
<h5>Example: https://www.google.com/#q=*</h5>
<input type="text" id="myText" placeholder="Enter a URL"> <button onclick="myFunction()">Submit</button>
<p id="demo">No Submitted URL</p>
<script>
function myFunction() {
var errors = [];
var x = document.getElementById("myText").value;
if (!x.includes("http://") && !x.includes("https://")) {
errors.push('missing HTTP or HTTPS');
}
if (!x.includes("*")) {
errors.push('missing * in place of query')
}
if (errors.length) {
x = 'Error: ' + errors.join(', ') + '!';
}
document.getElementById("demo").innerHTML = x;
}
</script>
You need to write the if condition correctly.
Change the condition from
if ( !x.includes("http://") || !x.includes("https://") ) {
to
if ( !(x.includes("http://") || x.includes("https://")) ) {
In this way, you raise the error only when the url doesn't contain either http:// or https://
Complete Code:
<!DOCTYPE html>
<html>
<head>
<title>Slingshot.XSS</title>
</head>
<body style="font-family:monospace;" align="center">
<h2>Slingshot.XSS</h2>
<h3>Slingshot.XSS is a script that launches pre-loaded XSS payloads at a target to test its vulnerabilities.</h3>
<h4>Please report all issues to or contact me at keeganjkuhn#gmail.com.</h4>
Source Code / Learn More
<br />
<h4>Enter a URL with <b>*</b> in the place of query.</h4>
<h5>Example: https://www.google.com/#q=*</h5>
<input type="text" id="myText" placeholder="Enter a URL"> <button onclick="myFunction()">Submit</button>
<p id="demo">No Submitted URL</p>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
// Error check
if ( !x.includes("*") && ( !x.includes("http://") || !x.includes("https://") ) ) {
document.getElementById("demo").innerHTML = "ERROR! MISSING \'*\' IN PLACE OF QUERY, \'http://\', AND \'https://\'!";
x = false;
return 0;
}
if ( !x.includes("*") ) {
document.getElementById("demo").innerHTML = "ERROR! MISSING \'*\' IN PLACE OF QUERY!";
x = false;
return 0;
}
if ( !(x.includes("http://") || x.includes("https://")) ) {
document.getElementById("demo").innerHTML = "ERROR! MISSING \'http://\', OR \'https://\'!";
x = false;
return 0;
}
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>

Categories