Timeout function for new tab - html

I have password protected a link that will open in a new tab but i now want that tab to timeout after a short while. I have tried this but to no avail, any help would be amazing!
<script>
var newWin;
function validatePass(){
if(document.getElementById('password').value == 'Techsoc'){
newWin = window.open('https://docs.google.com/spreadsheets/d/e/2PACX-1vRsNGb741vTBtSGlzbxnTsoZpFMs0l9ZMrD54uE4XGy6FvSMmNfp3RPWvDU3vI32iSIp07CEshGLo0M/pubhtml');
}else{
alert('Incorrect Password, please try again.');
return false;
setTimeout(function(){newWin.close()}, 5000);
}
}
</script>

The issue was with the timeout being within the else statement, when the new window have been created within the if. Now if you type in the password and click the button it should open the new tab and close after the time set in the timeout.
<input type="password" id="password"></input>
<button OnClick="validatePass()">Log In</button>
<script>
var newWin;
function validatePass() {
if (document.getElementById('password').value == 'Techsoc') {
newWin = window.open('https://docs.google.com/spreadsheets/d/e/2PACX-1vRsNGb741vTBtSGlzbxnTsoZpFMs0l9ZMrD54uE4XGy6FvSMmNfp3RPWvDU3vI32iSIp07CEshGLo0M/pubhtml');
setTimeout(
function () {
newWin.close()
}, 5000);
}
else {
alert('Incorrect Password, please try again.');
return false;
}
}
</script>

Related

Google sheet not being updated by setValues

I am writing a large file uploader for Google Drive and when I tried to implement writing some data to a Google Sheet I ran into a brick wall, for whatever reason I could not get it to ever write or even give a error as to why. I decided to start a whole new project and made it as simple as possible so all it does is grab similar data to what I will be grabbing and write it, but still no luck.
I am not super familiar with the Google Apps processes or the syntax of using them so I am probably just doing something really stupid.
Old code removed
I have tried removing some variables like file and email in case they needed to be written differently and changing how the form is passed to the function but the best I ever got was a "Cannot read Null" error when I passed it a form that didn't exist.
UPDATE:
Once I had it working I tried to slip it into the main script I am using (Which is basically a copy of this but now its not working, I am realizing this may be over my head unfortunately cause no matter what I try its doing the same, runs and uploads the file fine, but does not update the form.
Google Scripts:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Form.html');
}
function getAuth() {
return { accessToken: ScriptApp.getOAuthToken(), folderId: "1sFxs3Ga4xWFCgIXRUnQzCAAp_iRX-wdj" };
}
function setDescription({fileId, description}) {
DriveApp.getFileById(fileId).setDescription(description);
}
function updateform(formObject) {
try {
var ss = SpreadsheetApp.openById('1iCTNZ6RERnes1Y-ocfXzPN3jviwdIEK_dBKQ4LIu5KI');
var sheet = ss.getSheets()[0];
sheet.appendRow([myFile.getName(), myFile.getUrl(), formObject.myName], "If This Shows Up It Worked");
} catch (error) {
return error.toString();
}
}
HTML:
<form id="myForm" align="center" onsubmit="updatesheet(This)">
<input type="text" name="myName" placeholder="Your name..">
<input type="file" name="myFile">
<input type="submit" value="Submit Form" onclick="run(); return false;">
</form>
<div id="progress"></div>
<div id="output"></div>
<script src="https://cdn.jsdelivr.net/gh/tanaikech/ResumableUploadForGoogleDrive_js#master/resumableupload_js.min.js"></script>
<script>
function onSuccess() {
var div = document.getElementById('output');
div.innerHTML = '<a href="Spreadsheet Updated</a>';
}
function onFailure(error) {
alert(error.message);
}
function updatesheet(form) {
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).updateform(form);
}
function run() {
google.script.run.withSuccessHandler(accessToken => ResumableUploadForGoogleDrive(accessToken)).getAuth();
}
function ResumableUploadForGoogleDrive({accessToken, folderId}) {
const myName = document.getElementsByName("myName")[0].value;
const file = document.getElementsByName("myFile")[0].files[0];
if (!file) return;
let fr = new FileReader();
fr.fileName = file.name;
fr.fileSize = file.size;
fr.fileType = file.type;
fr.readAsArrayBuffer(file);
fr.onload = e => {
var id = "p";
var div = document.createElement("div");
div.id = id;
document.getElementById("progress").appendChild(div);
document.getElementById(id).innerHTML = "Initializing.";
const f = e.target;
const resource = { fileName: f.fileName, fileSize: f.fileSize, fileType: f.fileType, fileBuffer: f.result, accessToken, folderId };
const ru = new ResumableUploadToGoogleDrive();
ru.Do(resource, function (res, err) {
if (err) {
console.log(err);
return;
}
console.log(res);
let msg = "";
if (res.status == "Uploading") {
msg = Math.round((res.progressNumber.current / res.progressNumber.end) * 100) + "% (" + f.fileName + ")";
} else {
msg = res.status + " (" + f.fileName + ")";
}
if (res.status == "Done") {
google.script.run.withSuccessHandler(_ => {
document.getElementById('myForm').style.display = 'none';
document.getElementById('p').style.display = 'none';
document.getElementById('output').innerHTML = "All information submitted, thank you!";
}).setDescription({fileId: res.result.id, description: "Uploaded by " + myName});
}
document.getElementById(id).innerText = msg;
});
}
}
</script>
Several things about your updated code.
First it should be this not This.
Second you have onsubmit and onclick events for the same form. I believe the onclick is suppressing the submit event. Remove onclick entirely.
Third you use a try catch block in updateform so withFailureHandler will never execute. Instead the error message or null is returned to the success handler onSuccess(error).
Forth, I use a paragraph <p> instead of an anchor <a>. The href is malformed in your anchor.
Last, run() can be executed in updatesheet(form). Note run() is asynchronous which means it doesn't wait for google.script.run to finish before executing.
I can simply tell you that all the alerts are displayed and the execution log shows updateform did execute. So this code works for me.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="myForm" align="center" onsubmit="updatesheet(this)">
<input type="text" name="myName" placeholder="Your name..">
<input type="text" name="myFile">
<input type="submit" value="Submit Form">
</form>
<div id="progress"></div>
<div id="output"></div>
<script>
function onSuccess(error) {
if( error ) {
alert(err);
return;
}
alert("onSuccess");
var div = document.getElementById('output');
div.innerHTML = "<p>Spreadsheet Updated</p>";
}
function run() {
alert("run");
}
function updatesheet(form) {
alert("updatesheet");
google.script.run.withSuccessHandler(onSuccess).updateform(form);
run();
}
</script>
</body>
</html>

IndexedDB transaction always throwing onabort from add() method in Chrome

I just started experimenting with IndexedDB. I copied an example and pared it down to a small HTML page: Push a button; add a record; dump all the records to the console after the transaction completes.
It runs fine in IE11, but not on Chrome.
The request=transaction.objectstore("store").add({k:v})is always executing the request.onsuccess() method, but the transaction is always resolved with transaction.onabort() by Chrome. Same with .put().
This is the code:
<!DOCTYPE html>
<html>
<head>
<script>
//--- globals
var db;
// The initialization of our stuff in body.onload()
function init() {
var dbVersion = 1;
//--- Try to delete any existing database
var delRequest = indexedDB.deleteDatabase("notesDB");
delRequest.onsuccess = function (de) {
dbOpen(); // .... then open a new one
};
delRequest.onerror = function (de) {
dbOpen(); // ... or open a new one if one doesn't exist to delete
};
function dbOpen () {
var openRequest = indexedDB.open("notesDB", dbVersion);
openRequest.onupgradeneeded = function (e) {
var ldb = e.target.result;
console.log("running onupgradeneeded; always start with a fresh object store");
if (ldb.objectStoreNames.contains("note")) {
ldb.deleteObjectStore("note");
}
if (!ldb.objectStoreNames.contains("note")) {
console.log("creating new note data store");
var objectStore = ldb.createObjectStore("note", { autoIncrement: true });
objectStore.createIndex("title", "title", { unique: false });
}
};
openRequest.onsuccess = function (e) {
db = e.target.result;
db.onerror = function (event) {
// Generic error handler for all errors targeted at this database
alert("Database error: " + event.target.errorCode);
console.dir(event.target);
};
console.log("Database opened; dump existing rows (shouldn't be any)");
displayNotes();
};
openRequest.onerror = function (e) {
console.log("Open error");
console.log(e);
console.dir(e);
};
}
function displayNotes() {
console.log("TODO - print something nice on the page");
var tx = db.transaction("note", "readonly");
tx.oncomplete = function (event) { console.log("read only cursor transaction complete"); }
tx.onerror = function (event) { console.log("readonly transaction onerror"); }
tx.onabort = function (event) { console.log("readonly transaction onabort"); }
// --- iterate cursor
console.log("---Start cursor dump---")
var ds = tx.objectStore("note");
ds.openCursor().onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
console.log(cursor.key);
console.dir(cursor.value);
cursor.continue();
}
else {
console.log("---End cursor dump---");
}
};
}
document.querySelector("#test").addEventListener("click", function (clickevent) {
try {
var transaction = db.transaction("note", "readwrite");
transaction.oncomplete = function (event) {
console.log("Cursor dump in 'add' read/write transaction oncomplete");
displayNotes();
console.log("add transaction oncomplete done!");
};
transaction.onerror = function (event) {
console.log("add transaction onerror");
};
transaction.onabort = function (event) {
console.log("add transaction onabort");
};
var objectStore = transaction.objectStore("note");
var request = objectStore.add({
title: "note header",
body: "this is random note body content " + Math.floor(Math.random() * 1000)
});
request.onsuccess = function (event) {
console.log("add request onsuccess");
};
request.onerror = function (event) {
console.log("add request onerror");
console.dir(event);
};
}
catch (e) {
console.log('catchall exception');
console.log(e);
alert("bad things done");
}
});
}
</script>
</head>
<body onload="init()">
<h1>IndexedDB simplest example</h1>
<p>
<button id="test">Push To Add Row To IndexedDB</button>
</p>
</body>
</html>
I clicked the button a bunch of times and it worked every time.
What error are you getting when it aborts? Look in event.target.error in the onabort handler to see. It could be a QuotaExceededError, which would mean that either you have very low hard drive space or you have a lot of data stored in Chrome for your domain. If that's the case, it's good you're running into it now, because you do need to gracefully handle this case, otherwise users will hit it and be confused.

Ajax form requires two clicks on submit before fades out

So there is obviously something wrong in my syntax. Validation is ok. When I click submit the form sends email to me and then it deletes the value of my inputs. Everything is ok until now. But it does not fade out as it should. If I click on submit again, then it fades out. Thanks!
<script type="text/javascript">
$(document).ready(function () {
$('#form1').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter a value for name');
return false;
}
if (!email[0]) {
alert('Please enter a value for email');
return false;
}
if (!message[0]) {
alert('Please enter a value for message');
return false;
}
else {
$("#form1").ajaxForm(function () {
$("#formplic").fadeOut(1000, function () {
$(this).html("<img src='images/postauto3.png'/>").fadeIn(2000);
});
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
}
}
});
OK. I figured it out. The issue was that after else I stated again ajax.Form. I deleted that line and it works pefectly. So, if someone makes the same mistake as me, delete $("#form1").ajaxForm(function ().

Chrome extension development: auto close the notification box

After doing something I run this code:
var notification = webkitNotifications.createNotification(
'icon.png', // icon url - can be relative
'Done!', // notification title
'Just updated your list!' // notification body text
);
notification.show();
which of course pops up a notification into the users screen.
It there anyway to time this notification so that it auto-closes in X amount of seconds?
Thanks!
R
You can use notification.cancel();
var notification = webkitNotifications.createNotification('images/icon-48x48.png',"This is Title","Biswarup Adhikari Notification");
notification.show();
setTimeout(function(){
notification.cancel();
},2000);
Chrome notification will close automatically after 2000 milli sec or 2 sec.
You'll be able to call window.close() from inside the notification's HTML page. That will close the notification.
To close at a certain time, calling something like setTimeout( function () { window.close(); }, timeInMicroseconds); should be effective.
function show(title, message, icon) {
try {
icon = icon || 'src/img/icons/icon48.png';
var self = this;
var isClosed = false;
var notificationId = "posting_" + Math.random();
chrome.notifications.create(notificationId, {
type: "basic",
title: title + "!",
message: message,
iconUrl: icon
}, function (nId) {
});
setTimeout(function () {
if (!isClosed)
chrome.notifications.clear(notificationId, function (wasCleared) {
});
}, 3000);
} catch (e) {
alert(e.message);
}
}
ok, when i created notification remeber the id notificationId and settimeout clear this id
//Use requireInternaction and set it to true for notification to not to auto-hide.
function showNotification() {
var options = {
body: 'The Subtitles will Go Here',
requireInteraction: true
};
if (window.Notification && Notification.permission !== "denied") {
Notification.requestPermission(function (status) { // status is "granted", if accepted by user
var n = new Notification('Title', options);
});
}
}

Jquery Click Event Not Firing On First Click, but does on second click, why?

I've got a jQuery code, which
$("a.reply").click(function() {
//code
});
When I click the link with .reply class the first time, nothing happens. The second time I click, the code inside the click function works.
The link is being inserted on the page using PHP from a mysql database. so it's not being inserted dynamically.
Why is this happening? Any solution?
The BadASS Code:
$(function(){
//TextArea Max Width
var textmaxwidth = $('#wrapper').css('width');
//Initialize Focus ids To Different Initially
var oldcommentid = -1;
var newcommentid = -2;
//End Of initialization
$("a.reply").click(function() {
newcommentid = $(this).attr('id');
if (newcommentid == oldcommentid)
{
oldcommentid=newcommentid;
$("#comment_body").focus();
}
else
{
$('#comment_form').fadeOut(0, function(){$(this).remove()});
var commetformcode = $('<form id="comment_form" action="post_comment.php" method="post"><textarea name="comment_body" id="comment_body" class="added_comment_body" rows="2"></textarea> <input type="hidden" name="parent_id" id="parent_id" value="0"/> <div id="submit_button"> <input type="submit" value="Share"/><input type="button" id="cancelbutton" value="Cancel"/></div></form>');
commetformcode.hide().insertAfter($(this)).fadeIn(300);
//
var id = $(this).attr("id");
$("#parent_id").attr("value", id);
oldcommentid=newcommentid;
//dynamicformcreation function
dynarun();
//
}
return false;
});
dynarun();
function dynarun()
{
//Form Re-Run Functions
$('#comment_body').elastic();
texthover();
$("#comment_form input, select, button").uniform();
textareasizer();
$("#comment_body").focus();
$("abbr.timestamp").timeago();
return false;
}
//TextArea Resizer Function
function textareasizer(){$("#comment_body").css('max-width', textmaxwidth);return false;}
//Other Miscellaneous Functions
$('.comment-holder').hover(
function(event) {
$(this).addClass('highlight');
},
function(event) {
$('.comment-holder').removeClass('highlight');
}
);
function texthover()
{
$('.added_comment_body').hover(
function(event) {
$(this).parent().parent().addClass('highlight');
},
function(event) {
$('.comment-holder').removeClass('highlight');
}
);
return false;
}
});
This is a longshot, but are you running some sort of tracking script? Like webtrends or coremetrics (or even some of your own script, that's globally looking for all clicks)? I ran into a similar problem a while ago, where the initial-click was being captured by coremetrics. Just a thought.
Does it still happen if you comment out all your code and simply have an alert("hi") inside the click function?
Update
I think Sarfaz has the right idea, but I would use the document ready function like so
$(document).ready(function(){
$("a.reply").click(function() {
//code
});
});
I just ran into same problem and I resolved my problem by removing:
<script src="bootstrap.js"></script>
you can use bootstrap.min.js
Use Inline CSS for hiding div and use JS/jQuery to show . This way Jquery Click Event will Fire On First Click
<div class="about-block">
<div class="title">About us</div>
<div class="" id="content-text" style="display:none;">
<p>Show me.</p>
</div>
</div>
<script>
var x = document.getElementById("content-text");
jQuery( '.about-block' ).click(function() {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
});
</script>