With the best of my abilities (absolutely not a dev), I'm trying to developp a Chrome extension that resume a Netflix session on another computer.
When I click the extension, the current URL of the tab is sent to another computer and there the URL is captured and a Netflix is started.
And it works!
1) But I'd like the current TAB to be paused, so simulate the sending of the SPACE key.
Please do you know how I can do that?
2) Also, when I click on the plugin, I then have to click on the "Save bookmark" button to actually send the link.
Please is there a way to just send the link when I'm actually clicking on the plugin : basically the link is sent without having to click on "Save bookmark"?
I know these are super noob questions, I tried to find myself, but I'm really really bad at this!
Thank you in advance!
popup.js
// This callback function is called when the content script has been
// injected and returned its results
function onPageDetailsReceived(pageDetails) {
document.getElementById('title').value = pageDetails.title;
document.getElementById('url').value = pageDetails.url;
document.getElementById('summary').innerText = pageDetails.summary;
}
// Global reference to the status display SPAN
var statusDisplay = null;
// POST the data to the server using XMLHttpRequest
function addBookmark() {
// Cancel the form submit
event.preventDefault();
// The URL to POST our data to
var postUrl = 'http://192.168.0.16/netflix/index.php';
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed by URLEncoding each field's contents
var title = encodeURIComponent(document.getElementById('title').value);
var url = encodeURIComponent(document.getElementById('url').value);
var summary = encodeURIComponent(document.getElementById('summary').value);
var tags = encodeURIComponent(document.getElementById('tags').value);
var params = 'title=' + title +
'&url=' + url +
'&summary=' + summary +
'&tags=' + tags;
// Replace any instances of the URLEncoded space char with +
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Saved!';
window.setTimeout(window.close, 1000);
} else {
// Show what went wrong
statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
}
}
};
// Send the request and set status
xhr.send(params);
statusDisplay.innerHTML = 'Saving...';
}
// When the popup HTML has loaded
window.addEventListener('load', function(evt) {
// Cache a reference to the status display SPAN
statusDisplay = document.getElementById('status-display');
// Handle the bookmark form submit event with our addBookmark function
document.getElementById('addbookmark').addEventListener('submit', addBookmark);
// Get the event page
chrome.runtime.getBackgroundPage(function(eventPage) {
// Call the getPageInfo function in the event page, passing in
// our onPageDetailsReceived function as the callback. This injects
// content.js into the current tab's HTML
eventPage.getPageDetails(onPageDetailsReceived);
});
});
event.js
// This function is called onload in the popup code
function getPageDetails(callback) {
// Inject the content script into the current page
chrome.tabs.executeScript(null, { file: 'content.js' });
// Perform the callback when a message is received from the content script
chrome.runtime.onMessage.addListener(function(message) {
// Call the callback function
callback(message);
});
};
popup.html
<body>
<form id="addbookmark">
<p><label for="title">Title</label><br />
<input type="text" id="title" name="title" size="50" value="" /></p>
<p><label for="url">Url</label><br />
<input type="text" id="url" name="url" size="50" value="" /></p>
<p><label for="summary">Summary</label><br />
<textarea id="summary" name="summary" rows="6" cols="35"></textarea></p>
<p><label for="tags">Tags</label><br />
<input type="text" id="tags" name="tags" size="50" value="" /></p>
<p>
<input id="save" type="submit" value="Save Bookmark" />
<span id="status-display"></span>
</p>
</form>
</body>
Related
I am new to NodeJS . I want to send data to page with redirect multiple parameters like html form as below :
<form action="https://example.com/payment.aspx" method="post">
<input type="hidden" name="Amount" value="5000"/>
<input type="hidden" name="ResNum" value="sdsadasd231323"/>
<input type="submit" id="startBankPayment" class="btn btn-lg btn-success col-md-5" value="startPayment"/>
</form>
I need a sample code send data to url and redirect to this url like form submit button clicked ?
function submitForm(){
var a = document.getElementById('Amount').value;
var b = document.getElementById('ResNum').value;
var holder = {Amount : a, ResNum : b};
var xhr1 = new XMLHttpRequest();
xhr1.open('POST', "https://example.com/payment.aspx", true);
xhr1.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
//ADD CODE to redirect my page when I get my data back
}//
};//end onreadystate
xhr1.send(JSON.stringify(holder));//the object you are sending
}
Here is a sample that should help. You execute this function when your button is clicked, so you need to add the click="submitForm()" to your button. You also need to add id="Amount" and id="ResNum" to those fields. You also wouldn't need the form action anymore since this takes care of the actual post. You also need to know how the form is being read on the server end and what type of encoding you need. You may be able to send as form encoded data or you may need to JSON.stringify() the object before you send it off incase it is parsed as jsonencoded data, which I included.
Below is a program that I put together, from research and some of my own adding, and I'm having many issues with it. The record_submission function isn't working properly. Every time I test with someone submitting their name, it won't properly record the information which then effects the next function, the notification function which I wrote to automatically send me an email once someone submits a response. Would appreciate some help.
Attached are the images of the Google spreadsheet that I want updated whenever someone submits a response as well as the face of the website people will be submitting information from. The record function is supposed to do that. It's giving me a error saying that the variable isn't properly assigned or something of the sort and the notification email doesn't work properly either.
This is the whole JavaScript code:
//* This function handles the get request from the web browsers */
function doGet(e)
{
//return form.html as the response return
HtmlService.createHtmlOutputFromFile('form.html');
}
// Record all the information entered into the form into a Google Sheet.
function record_submission(form)
{
Logger.log(form);
var ss = SpreadsheetApp.openById("1dQQ1b3NjeYgVEOLIaSNB-XCZwAPAQr6C85Wdqj-sBM8");
var sheet = ss.getSheets()[0]; // Assume first sheet collects responses
// Build a row of data with timestamp + posted response
var row = [ new Date(), // Timestamp
form.last_name[0], // last name
]; // Make sure we are the only people adding rows to the spreadsheet
var lock = LockService.getPublicLock(); // Wait for up to 30 seconds for other processes to finish.
var locked = lock.tryLock(30000);
if (locked)
{
// Save response to spreadsheet
var rowNum = sheet.getLastRow() + 1;
sheet.getRange(rowNum, 1, 1, row.length).setValues([row]);
// Release the lock so that other processes can continue.
lock.releaseLock();
var result = "Response Recorded: \n
"+row.join('\n ');
}
else
{
// Failed to get lock
result =
"System busy, please try again.";
}
// Report result of POST, in plain text
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.TEXT);
}
// Send an email to yourself notifying you when someone made a submission.
function notification(last_name, assignment_name)
{
var subject = "New Submission"; MailApp.sendEmail("*my email*#gmail.com",
subject, 'New submission received from ' + last_name + ' for the
assignment: ' + assignment_name );
}
/* This function will process the form when the submit button is
clicked */
function uploadFiles(form)
{
try
{
notification('test','test'); //Retrieve a reference to the folder in Google Drive
var folder_name = "Test_Folder"
var folder =
DriveApp.getFolderById("0By69oDzO6OluTm9KNGVuaUZZdE0");
// Create a new folder if the folder does not exist
if (!folder)
{
folder = folder.createFolder(folder_name);
}
//Get the file uploaded through the form as a blob
var blob = form.myFile;
var file = folder.createFile(blob);
//Set the file description as the name of the uploader
file.setDescription("Uploaded by " + form.LastName);
//Set the file name as the name of the uploader
file.setName(form.LastName + "_" + form.AssignmentName);
//This function should store the information of the submission to a Google Sheet
record_submission(form);
//This function should notify you when there has been a submission
notification(form.LastName, form.AssignmentName);
// Return the download URL of the file once its on Google Drive
return "File uploaded successfully " + file.getUr1();
}
catch(error)
{
// If there's an error, show the error mesage return
error.toString();
}
}
This is the whole HTML code
File Upload
<!--User inputs -->
<h4>First name</h4>
<input type="text" name="FirstName" placeholder = "Type your first name.." >
<h4> Last Name </h4>
<input type="text" name = "LastName" placeholder="Your last name...">
<h4> Assignment Name </h4>
<input type="text" name="Course" placeholder="Course number">
<!--File upload-->
<h4>Upload</h4>
<input type="file" id="file" name="myFile" style="display:block; margin: 20px;" value = "myFile">
<!-- Submit button -->
<input type="submit" value="Submit"
onclick= "this.value='Uploading..';
google.script.run.withsuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form> <div id="output"> </div> <script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
/*check to see if the user's first name input is empty.
If it is empty alert the user to fill in his/her first name */
</script>
<style>
input {display:block; margin: 20px; }
</style>
</body> </html>
I see that your 'input' tags are not wrapped in a 'form' tag, so what gets passed to the 'onclick' function as parameter might actually be the entire <body> tag. Are your inputs nested inside the <form> tag? If not, then this.parentNode would be the entire body of the HTML document.
I put together the quick example illustrating the entire process. On the client side, we are listening for the form submit event. Once the event fires, we call the server-side function via google.script.run and pass the form object to that function as an argument.
Code.gs
function onOpen(){
var ui = SpreadsheetApp.getUi();
ui.showSidebar(HtmlService.createHtmlOutputFromFile('sidebar')
.setTitle('siderbar'));
}
function logFormObject(form){
Logger.log(form); //check the logs by pressing Ctrl + Return
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]; // get the 1st sheet in the spreadsheet
sheet.appendRow([form.name, form.lastName, form.age]); //create row contents array from the form object and pass it to the appendRow() method
}
HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="myForm">
Name <br>
<input name="name" /> <br>
Last Name: <br>
<input name="lastName" /> <br>
Age: <br>
<input name="age" /> <br>
<input type="submit" value="send">
</form>
<script>
window.onload = function(){
var form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
event.preventDefault(); //prevents redirect to another page
google.script.run.logFormObject(this); // calling the server function in Code.gs
});
}
</script>
</body>
</html>
What I want is having a JavaScript function which sends a POST to an arbitrary site and stays the whole time on the site 'it was executed on'. It does not necessarily have to be done with a form!
I don't want to use jQuery, if possible.
How can I do this?
You can "prevent" the default behavior.
<form id="myform">
Name: <input id="name" type="text" value="onur" /><br />
Email: <input id="email" type="text" value="onur#email.com" /><br />
<br />
<button type="submit">type=submit</button>
<button type="button" onclick="form.submit()">form.submit()</button>
</form>
Before the </body> tag (or on DOM ready);
var form = document.getElementById('myform');
function onSubmit(event) {
if (event) { event.preventDefault(); }
console.log('submitting');
postFormData(form); // <-------- see below
}
// prevent when a submit button is clicked
form.addEventListener('submit', onSubmit, false);
// prevent submit() calls by overwriting the method
form.submit = onSubmit;
Fiddle here
EDIT:
The default behavior of form.submit() will redirect the page to the form.action URL. This is an approach on how you simulate the default behavior without redirecting to another page.
And since you want to "POST" the form, here is the method (AJAX stuff):
function postFormData(form) {
var xhr = new XMLHttpRequest(),
formData = urlEncodeFormData(form); // see below
// set XHR headers
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// watch for state changes
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
// This is where you show a success message to the user
}
};
// open and send the post request
xhr.open('POST', 'https://myweb.com/action-target', true);
xhr.send(formData);
}
// You could use the FormData API if the browser supports it.
// Below is somewhat alternate and should be improved to support more form element types.
function urlEncodeFormData(form) {
var i, e, data = [];
for (i = 0; i < form.elements.length; i++) {
e = form.elements[i];
if (e.type !== 'button' && e.type !== 'submit') {
data.push(encodeURIComponent(e.id) + '=' + encodeURIComponent(e.value));
}
}
return data.join('&');
}
See:
MDN — Using XMLHttpRequest
MDN — FormData
Can I Use FormData?
Give your form an onsubmit handler that returns false. Do whatever processing you need to do in there (eg: ajax send data or what have you)
Code's untested, but here's the general idea.
function doFormThings() {
//processing form here
return false; //don't actually redirect, browser, I'm watching you
};
<form onsubmit="return doFormThings();">
Since you are dynamically creating the form, you can create it in an iframe and submit it inside of the iframe - that way you won't leave the current page and you'll actually use normal form submit. Here is a working example:
function generateFormAndSubmit()
{
// Create an input for the form
var input = document.createElement( 'input' );
input.type = 'hidden';
input.name = 'test'
input.value = '123';
// Create the form itself
var form = document.createElement( 'form' );
form.action = '/myaction';
// Append the created input to the form
form.appendChild( input );
// Create the iframe that will hold the form
var iframe = document.createElement( 'iframe' );
// Make it offscreen, so it's not visible for the user
iframe.style.cssText = 'width: 1px;height: 1px;position: absolute;top: -10px;left: -10px';
// Append the iframe to our document
document.body.appendChild( iframe );
// Append the form to the iframe
iframe.contentDocument.body.appendChild( form );
// Submit the form
form.submit();
}
You can call the submit of the form from another place, of course, like a button for an example - the iframe is yours, so you can manipulate (search for the form, modify it, submit it, etc.) it's contents at any point - no security restrictions will apply.
If you need a result of the submit, then it's a bit more complicated - first, the action of the form needs to point to the same domain. Then, if that is true, you just listen for when the iframe is loaded and read the result from it's content (either printed in the document JS or parse the DOM in some way).
You can simply have an iframe and change the form's target to post the data into it. E.g:
<form method='POST' target='hd-submit'>
<input name='firstName' placeholder='First Name' type='text' />
<input name='lastName' placeholder='Last Name' type='text' />
<input type='submit' value='Send' />
</form>
<iframe name='hd-submit' hidden></iframe>
So on my page, I have a button where user can export the data to EXCEL/PDF. The way it works is they click on the button and then I send the data into a hidden form which submits the request. Once the request is done, it returns the content of the document type that the user selected which prompts the "Save As" dialog.
<form id="export-form" action="laravel-excel.php" method="POST" target="hidden-form">
<input type="hidden" name="type" value="{{header.export.type}}" />
<input type="hidden" name="name" value="{{header.export.name}}" />
<input type="hidden" name="data" value="{{header.export.data}}" />
</form>
<iframe style="display:none" name="hidden-form"></iframe>
So everything works as it should! However, I want to add a loader to let people know that the file is processing and when its done, I want to hide it. Well based on my research I was unable to find a solution that works for forms. The solutions I found are ones where the processing happens via AJAX like so:
$('#export-form').ajaxForm({
success: function (response, status, request)
{
var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') != -1)
{
var type = request.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
window.location = downloadUrl;
}
}});
Is there a better solution out there?
I need a button to call a php page though ajax. I need the button to open the client's email with a mailto link. The php page generates the email, which consist of an encrypted string that passes credentials to a secured site.
Basically, I need these things to happen in this order:
Click the button.
Make the ajax call.
Populate href with "mailto:subject=your_secret_link&body=http://securesite.com?authcode=encrytpedstuff"
Open the client's email.
I've tried this:
html part:
<span id="mailframe"><input name="Request Signing via Email" value="Request Signing via Email" type="button" class="redButton" onclick="sendEmail();"/></span>
javascript part
function sendEmail() {
var hash=document.getElementById('hash').value;
var obj=document.getElementById('mailframe');
var email=document.getElementById('myemail');
var mailxml = new XMLHttpRequest;
mailxml.onreadystatechange = function() {
if ((mailxml.readyState == 4) && ((mailxml.status == 302)|| (mailxml.status == 200))) {
email.href=mailxml.responseText;
}
}
mailxml.open("GET",'/secure/literature/generateid.php?hash='+hash+'&docid=<?=$docid?>' );
mailxml.send();
}
It works in IE, but not in Firefox. Any ideas?
I think that you need something like this (works with FireFox 24):
<script type="text/javascript">
function sendEmail() {
var hash=document.getElementById('hash').value;
var email=document.getElementById('myemail');
var mailxml = new XMLHttpRequest;
mailxml.onreadystatechange = function() {
if (mailxml.readyState == 4 && ((mailxml.status == 302) || (mailxml.status == 200))) {
window.location.href = mailxml.responseText;
}
};
mailxml.open("GET", "/your/long/url?with=parameters", true);
mailxml.send();}
</script>
<div>
<input type="button" onclick="sendEmail()" value="Send E-mail"/>
<input type="text" name="hash" id="hash" value="hashValue" />
E-mail link
</div>
Also check Easiest way to retrieve cross-browser XmlHttpRequest and braces in code.