Reload a GAS's web app embedded on google sites - javascript

I have a webapp embedded in a new google site. This app embedded necessarily must reload the web app. When the web app's form is completed, the app open a modal with a button that call this function:
function reloadPage(){
google.script.run
.withSuccessHandler(function(url){window.open(url,"_top");})
.getScriptURL();
}
And this server side function:
function getScriptURL() {
var url = ScriptApp.getService().getUrl();
console.log(url)
return url ;
}
My console register this error:
Unsafe Javascript attempt to initiate navigation usserCodeAppPanel:150 for frame with origin “https://sites.google.com” from frame with URL”URL”. The frame attempting navigation of the top-level window is sandboxed, but the flag of ‘ allow-top-navigation' or ‘allow-top-navigation-by-user-activation’ is not set.
I need to do a reload because the form registers a value in a sheet. My app verifies that the value I will enter is not repeated on the sheet. So after submitting the form, the value just registered is not reflected. For example, I enter the ID 1, the validator looks for that value in the worksheet. If it does not find it, it allows you to enter it, otherwise it sends an alert. After submitting the form the fields are cleared, I re-enter ID 1 then the validator lets it pass because it verifies that 1 is not on the spreadsheet. So with a recharge this problem does not happen.
There's a way to reload the app without this error?
Greetings!

I found a solution:
First on my html header put the next line:
<base target="self">
I change my javascript function to this:
function reloadPage(){google.script.run.withSuccessHandler(function(url){window.open(url,"_self");}).getScriptURL();}
In my doGet function i put this:
function doGet(e){
var output = HtmlService.createTemplateFromFile('index');
return output.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}
With all this changes i get solved my problem. Thanks for the comments! Greetings!

Related

Javascript file for multiple html pages

I am beginner in Javascript. I am currentlyworking on a Phonegap app with it. I am stuck in between as I have 4 html pages for signup process, and I have to pass all the html pages input value to single js file as in final all data must be POSTed to server URL and also I have read on many sites that they have recommended using same js file for all the pages of your site to speed up the site. So I have two problems to solve. I searched on many sites but could not find the accurate answer.
I need to pass 4 html page's input value to single js file.
I have to make single js file for both sign-in and sign-up.
My codes for JS page is:
var firstName="";
var lastName="";
var email="";
var password="";
var retypePassword="";
var gender="";
var DOB="";
var institute="";
var course="";
var branch="";
var semester="";
var teachers = [];
function signUpStarting() {
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword+" "+gender+" "+DOB+" "+institute+" "+course+" "+branch+" "+semester+" "+teachers.join(","));
}
function signUp1() {
firstName[0] = $("#first_name").val().trim();
firstName[1] = $("#last_name").val().trim();
email = $("#email").val().trim();
password = $("#password").val();
retypePassword = $("#retype_password").val();
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword);
}
function signUp2() {
gender = $('#gender').find(":selected").text();
DOB = $('#DOB').val();
alert(gender+" "+DOB);
}
function signUp3() {
institute = $('#institute').find(":selected").text();
course = $('#course').find(":selected").text();
branch = $('#branch').find(":selected").text();
semester = $('#semester').find(":selected").text();
alert(institute+" "+course+" "+branch+" "+semester);
}
function signUp4() {
$(":checkbox" ).map(function() {
if($(this).is(':checked')){
teachers.push($('label[for="' + this.id + '"]').text());
}
});
signUpStarting();
}
In html pages I am calling JS functions for each pages:
On first page:
<a onclick="signUp1()" href="register-two.html">continue</a>
On second page:
<a onclick="signUp2()" href="register-three.html">continue</a>
On third page:
<a onclick="signUp3()" href="register-four.html">continue</a>
On fourth page:
<a onclick="signUp4()">continue</a>
On each transaction from one page to next I have set alert in JS, and I am getting alert with accurate values also. But after clicking the continue button from fourth page of html, I transferred the code to main signup function. I tried to see alert in signUpStarting() function but there I am getting response of just fourth page values and other values are showing nothing as the variables are null.
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
Please help me !
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
This is exactly right. You cannot store data in memory between page loads in a web browser environment because all javascript variables are naturally destroyed when the browser navigates away from the page to a new page (even if they use the same javascript on both pages). Thus, you have to save it somewhere with more permanence: localStorage, cookies, or on the server via POST or GET.
What I would recommend is scrapping the four different html pages and simply using one html page that changes dynamically as the user fills in data. This way the browser will not eliminate data before you are ready to POST it to the server.

change window's href on refresh

I am trying to change window's href on every refresh.
This is some url I have- http://localhost:2090/Meeting/CreateMeeting/?scope=&code=vGgoJvYi
Now I wished to have it as- http://localhost:2090/Meeting/CreateMeeting/
Tried-
window.onbeforeunload = function () {
window.location.href = "/Meeting/CreateMeeting/";
}
This didn't work-
So I tried it with an hidden anchor-
and then-
window.onbeforeunload = function () {
$('#click-url').click();
}
But I failed with this also.
How Do I make this url without parameters ?
Edit-
I am using some webservice to accept parameters from current url. So basically I have some form and on its submit it generates this url with parameter after redirecting from some api. My further process depends on this url.
if you note at url-
?scope=&code=vGgoJvYi
For every request from user that web api generates &code and it is unique.
If user tries to refresh the page then this code can only be coming after re-submitting the form. So further process is only be done with this generated code.
This is why I am trying to change the url without parameters because this ?scope=&code=vGgoJvYi will be coming after redirected from webApi.

How do I refresh a value in php from javascript?

I have a form that I'm submitting using javascript. However, one of the checks it does uses a php script that queries an API and gets a user's password. This is for the purposes of form validation (i.e. if password doesn't match what we have on file..)
I'm using a php script to decode the password like this
function submitForm() {
var options = {
decoded_password: '<?php echo abc_decode($contactInfo['Password'])?>',
}
if (jQuery('#current_password').val() != options.decoded_password && $psc('#current_password').val()) {
render_alert('Your current password does not match what we have on file.');
return false;
} else {
$psc('#account-information').submit();
document.getElementById("account-information").reset();
}
Page loads, great, submit form, great. However, the variable is remembered from the first page load, so if I try to change the password again, it says my password doesn't match what is on file. If I reload the page, no problem.
Is there any way to change the value of $contactInfo['Password'] in javascript without a page reload?
You could try making an AJAX call instead. This won't require a page reload, but will still give you the opportunity to send the data back to the server. If you store the data in the $_SESSION variable it will persist across multiple calls.

How to Call Google Apps Script from Web Page

Have searched high and low for this. I have a web page of basic HTML/CSS/JS. I want users to be able to visit the page and upon opening page, a call is made to a google script I made which takes information from a spreadsheet and displays some of it on the page. I am hoping I don't have to do any fancy set up like in Google's tutorials because none of them were helpful to me.
My Webpage ----> Google Script ----> Google Spreadsheet
My Webpage <---- Google Script <---- Google Spreadsheet
Users should be able to select an item shown on the webpage (item populated from spreadsheet) and click a button which will allow users to enter a new page with a URL derived from the selected item.
This is essentially a chat room program where the chat rooms are stored on a spreadsheet. I want users to be able to create a new chat room as well which should update the google spreadsheet.
Look into using the GET parameters. https://stackoverflow.com/a/14736926/2048063.
Here's a previous question on the topic.
You can access the parameters passed by GET in your doGet(e) function using e.parameter. If you call http://script.google......./exec?method=doSomething, then
function doGet(e) {
Logger.log(e.parameter.method);
}
doSomething will be written to the log, in this case.
Returning data from the script can be done using the ContentService, which allows you to serve JSON (I recommend). JSON is easiest (in my opinion) to make on the GAS end, as well as use on the client end.
The initial "populate list" call would look something like this. I will write it in jQuery because I feel that is very clean.
var SCRIPT_URL = "http://script.google.com/[....PUT YOUR SCRIPT URL HERE....]/exec";
$(document).ready(function() {
$.getJSON(SCRIPT_URL+"?callback=?",
{method:"populate_list"},
function (data) {
alert(JSON.stringify(data));
});
});
And the corresponding GAS that produces this.
function doGet(e) {
if (e.parameter.method=="populate_list") {
var v = {cat:true,dog:false,meow:[1,2,3,4,5,6,4]}; //could be any value that you want to return
return ContentService.createTextOutput(e.parameter.callback + "(" + JSON.stringify(v) + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
}
This method is called JSONP, and it is supported by jQuery. jQuery recognizes it when you put the ?callback=? after your URL. It wraps your output in a callback function, which allows that function to be run on your site with the data as an argument. In this case, the callback function is the one defined in the line that reads function (data) {.

global variables doesn't change value in Javascript

My project is composed by 2 html pages:
index.html, which contains the login and the registration form.
user_logged.html, which contains all the features of a logged-in user.
Now, what I want to do is a control if the user is really logged in, to avoid the case where a user paste a url in the browser and can see the pages of another user.
hours as now, if a user paste this url in the browser:
www.user_loggato.html?user=x#profile
is as if logged in as user x and this is not nice.
My html pages both use js files that contains scripts.
I decided to create a global variable called logged inizialized to false and change the variable to true when the login is succesful.
The problem is that the variable, remains false.
here is the code:
var logged=false; (write in the file a.js)
while in the file b.js I have:
function login() {
//if succesfull
logged=true;
window.location.href = "user_loggato.html?user="+ JSON.parse(str).username + #profilo";
Now with some alerts I found that my variable logged is always false. Why?
Javascript is not the way to go, as it runs on the client side. Even if there would be a way to share javascript variables between different requests, the user could manipulate them.
You have to take a server side technique for this (maybe PHP with sessions).
JS variables will reset on every submit/refresh. You could use sessionStorage or cookies for this purpose. For example:
Put this in your login form:
function login() {
window.sessionStorage[logged] = true;
window.location.href = "user_loggato.html?user="+ JSON.parse(str).username + #profilo";
}
And in your user_loggato.html, you can retrive it like:
function getLoginStatus() {
return window.sessionStorage['logged'];
}
Hope this helps.

Categories