Chrome extension form input text is blank on submit - javascript

I'm trying to build a chrome extension that downloads a bunch of items from links, the main logic is in my download.js file and I want to be able to specify in which downloads subfolder I'd like to bundle them all but the value of the input field seems to be empty. Here's my code so far
popup.html
<!doctype html>
<html>
<head>
<title>Download CVs</title>
<script src="popup.js"></script>
</head>
<body>
<form id="folderForm">
Subdir of downloads:
<input type="text" id="folder">
<input type="submit" id="download" value="Download CVs">
</form>
</body>
</html>
popup.js
function bundleItems() {
chrome.tabs.executeScript({
file: 'download.js'
});
}
document.addEventListener('DOMContentLoaded', function() {
var downloadButton = document.getElementById('download');
downloadButton.addEventListener('click', bundleItems);
});
chrome.extension.onRequest.addListener(function(logs) {
var folder = document.getElementById('folder').value;
logs.map(function(log) {
chrome.downloads.download({
url: log.attachment.link,
filename: folder + '/' + log.attachment.filename
});
});
});
I'm sending information from download.js to popup.js and everything works if I try to download it in downloads, so I feel posting my download.js file will be useless. However, if I try to display the folder variable, it's empty. I've searched for lots of other posts on the same issue and none of the solutions seem to work for me.

You cannot submit to a Chrome extension page. There is no web server to process your POST request in this case. Doing so simply reloads the document (clearing your value from the form).
You need to prevent submitting instead, by specifying type="button" for your button.

I would add preventDefault() on submit button.
https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault

Related

strange filename callback after file selection finish

I have this code which will display the file name after file has been selected:
<input id="file-input" type="file" />
<script>
const fileInput = document.querySelector('#file-input');
fileInput.onchange = function(){
console.log('file name:', this.value)
}
</script>
I prepared two windows shortcut file (produced by Desktop ---> right click ---> new ---> shortcut)
the first shortcut file
the target is https://www.baidu.com/ and the file name is www.baidu.com
after i select this file, the output is C:\fakepath\www.baidu.com.url in callback, which is working as expected
the second shortcut file
target is https://www.google.com/ and the file name is www.google.com
but after select this file, i expect it to output C:\fakepath\www.google.com.url in callback, but it outputs something like C:\fakepath\TQCJEVEM
Why is this happening?
Disclaimer: I'm still not sure about the why, but I can make a guess about what is happening.
When you create a windows shortcut (like you mentioned above) where the target is a Network Resource, it creates a URL file that has a .url extension.
NOTE: Microsoft Windows does not display the ".url" file extension even though it exists in the filename. Therefore, URL files saved using Windows web browsers will appear with only the filename prefix.
A URL file on windows looks something like this:
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,11
[InternetShortcut]
IDList=
URL=https://www.baidu.com/
HotKey=0
When you upload the baidu shortcut, windows simply uploads the file with above content.
HOWEVER
When you upload the google shortcut, windows actually downloads a copy of the www.google.com website landing page, stores it in the local cache somewhere in the ..\AppData\Local\Microsoft\Windows\INetCache\.. folder and then uploads that cache file which could have its filename as a randomly generated string. Every new attempt would generate a new string for filename.
Hope this points you in the right direction.
Edit:
To verify the content of the uploaded file, slightly modify your code using sample code from this answer.
function init() {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event) {
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>

jQuery/ Javascript .get method for reading text files

I just started working on my school assignment with some regular expressions in Javascript. I can't seem to figure out how to actually read data from a text file into variable using jQuery method .get(). When I try my code out nothing happens. It seems like it never enters .get() section. Here is my code:
JS file:
document.getElementById('file').onchange = function(){
var file = "New Text Document.txt"; //this will later be the selected file
$.get(file,function(data){
var myVar = data;
$("#123").html(myVar);
});
};
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>animacija</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file">
<script type="text/javascript" src="func.js"></script>
<div id="123"></div>
</body>
</html>
The code snippet seems to be ok, but it will not work locally since $.get is for ajax requests and requires full available server path.
I rather recommend you the use of FileReader API.
HTML
<title>animacija</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<input type="file" name="file" id="file">
<div id="123"></div>
</body>
JavaScript
document.getElementById('file').onchange = function() {
var file = this.files[0];
var FR = new FileReader();
FR.readAsText(file);
FR.onload = function(data) {
var myVar = data.target.result;
$("#123").html(myVar);
}
};
JSFiddle
Hope it works for you!
Most browsers will not allow file: resources to read other local files. This is to prevent attacks where a downloaded HTML document could start reading (and transmitting) the contents of your hard drive (or at least your Downloads folder) as soon as you open it.
The other thing you need to know here is that $.get is used for getting resources from an HTTP server, while file inputs are used to allow a user to select a file from their local drive. I realize in your case it's a little confusing, because your web page is on your local hard drive, but imagine if your HTML and scripts were being hosted online, and some other user (not you) was using them to process their own locally-stored files.
MDN has a good tutorial on how to get started with <input type="file"> inputs.
The code won't work locally due to cross-origin limitations.
It works fine when run on a remote server and all files are in the same folder.
If you want to read local files (aka. files selected by user through the file input) you can read more about FileAPI here:
https://www.html5rocks.com/en/tutorials/file/dndfiles/

Unable to call chrome api from script inside HTML

I am new to Javascript as well as Chrome extension development. I was trying to open a tab when the user clicks on the extension button. This is how my popup.html looks like
<!DOCTYPE html>
<head>
<title> Qoogle Homepage</title>
<script type="text/javascript">
var newURL = chrome.extension.getURL('qoogle.html');
chrome.tabs.create({ url: newURL });
</script>
</head>
</html>
I have declared the tabs permission in my manifest.json and qoogle.html lays in the same directory. But when I click on the extension, nothing happens.
Now, I tried to include <script src="popup.js"></script> line into my popup.html and then wrote
var newURL = chrome.extension.getURL('qoogle.html');
chrome.tabs.create({ url: newURL });
inside the popup.js file. This works fine.
I don't want too many files in my folder. What could be the reason my script does not get executed from the HTML and works fine when added separately as a JS file?
As stated in the Docs:
https://developer.chrome.com/extensions/contentSecurityPolicy#JSExecution
Inline JavaScript will not be executed
Check out this answer as well: https://stackoverflow.com/a/27913209/3052648

Chrome Extensions: Pass data from popup to another script file before the script is injected

Problem
Let's assume I go to a website called RENT.com. Let's also assume for this chrome extension there is a script A (JS) that is injected to RENT.com. Script A is a large script file that does a lot of interacting with RENT.com's HTML elements such as form fields. Before the script runs however, it needs some DOM ID's of a couple elements such as the email field because it modifies them.
Objective
I'd like to create a couple input fields (let's call them InputEmail and InputName) in popup.html to enter in the ID's of the elements on RENT.com. Obviously I'd be looking up the ID's manually by viewing the source, this is intentional.
A button in popup.html let's call it "GO BUTTON" will then read the value of InputEmail and InputName and send it to Script A. Script A now has everything it needs to function properly and is now injected into the page.
The appropriate interactions from Script A and RENT.com are now completed.
I've tried a few things, read a ton of information from Docs and Stack but I don't understand I think fundamentally how this can work. I want to pass data to Script A via popup.js before I execute content_script which ultimately is just injecting Script A. Seems like a chicken/egg problem and I'm not hungry for breakfast or lunch ;).
Thanks guys!
popup.html
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
</head>
<body>
<ul>
<li><label>Email ID</label><input type="text" id="emailID"></input></li>
<li><label>Company ID</label><input type="text" id="nameID"></input></li>
</ul>
<input type="button" id="Modify" style="" value="GO BUTTON"></input>
<script src="popup.js"></script>
</body>
</html>
Popup.js
function click(e) {
//Ideally pass these values to Script A somehow
var email = document.getElementById("emailID").value;
var company = document.getElementById("nameID").value;
//then execute this or pass the ID's to content_script, inject into Script A, then inject into page
chrome.tabs.executeScript(null, {file:"contentscript.js"});
window.close();
}
document.addEventListener('DOMContentLoaded', function () {
var d = document.getElementById("Modify");
d.addEventListener('click',click);
});
ContentScript to inject Script A
var s2 = document.createElement('script');
s2.src =chrome.extension.getURL("ScriptA.js");
s2.async = false;
s2.onload = function() {
s2.parentNode.removeChild(s2);
};
(document.head||document.documentElement).appendChild(s2);
There are several ways to accomplish this. One would be:
function click(e) {
var elementIDs = {
email: document.getElementById("emailID").value,
company: document.getElementById("nameID").value
};
chrome.tabs.executeScript({
code: 'window.elementIDs='+JSON.stringify(elementIDs)
}, function() {
chrome.tabs.executeScript({file: "ScriptA.js"});
});
window.close();
}
This way, ScriptA will be able to access the values in window.elementIDs. This will work because content scripts from the same extension on the same page will share the execution environment, and the chaining of the calls to chrome.tabs.executeScript ensures that the script defining the global variable has run before ScriptA is run.

problem with jquery post data to jsp page

I have the following html page Index.html , script.js and calculate.jsp file when i run the html page and hit submit button using tomcat server it gives error saying calculate.jsp file not found .Is their any syntax problem in the javascript file to call the jsp page .
<html>
<head>
<title>Simple jQuery and JSP example</title>
<script src="jquery-1.4.2.js" type="text/javascript"></script>
<script src="SCRIPT.js" type="text/javascript"></script>
</head>
<body>
<form id="form" action="calculate.jsp" method="post">
Enter number:
<input id="number" type="text" name="number" />
<input id="submit" type="submit" value="Calculate Square Root" name="submit"/>
</form>
<p id="result"></p>
</body>
</html>
Javascript file SCRIPT.js
$(document).ready(function() {
$('#form').submit(function() {
var number = $('#number').val();
$.ajax({
type: "post",
url: "calculate.jsp",
data: "number=" + number,
success: function(msg) {
$('#result').hide();
$("#result").html("<h3>" + msg + "</h3>")
.fadeIn("slow");
}
});
return false;
});
});
calculate.jsp
<?xml version="1.0" encoding="UTF-8" ?>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
int number = 0;
if(request.getParameter("number").matches("[\d]+")) {
number = Integer.parseInt(request.getParameter("number"));
out.println("Square root of " + number + " is " + Math.sqrt(number));
}
else {
out.println("Enter a number!");
}
%>
Here are some steps you can do to find out what is going wrong :
Add a console.log("submitting the form") at the first line in $('#form').submit function.
Add another print console.log("got message") in the "success" callback.
You can use chrome, Firefox+Firebug or IE 8 and above for this.
I usually use chrome and my following instructions refer specifically to chrome as it is easiest with it.
Click ctrl+j in chrome to open the developer's panel.
Go to 'Network'.
Reload "index.html" (your main page)
Make sure there are no errors displayed in the console below. ( if there are please post them here or handle them).
Assuming there are no errors : you should see your print "submitting the form" and a network call to "calculate.jsp" on the developers panel.
you can click on it to see the details - see the URL you are actually requesting for. is this the URL you expected?
Copy paste the URL you see and copy it on a new tab. This will give you a sufficient workspace to handle any problems on that page.
The above steps should give you sufficient clues as to what is the problem and how to resolve it.
In order to verify that your code is working properly - you should see your "got message" print and the content in the HTML from calculate.jsp.
I also recommend opening the network and verifying that the response you get from "calculate.jsp" is correct.
let me know if you experience any new problems.

Categories

Resources