Javascript code not displaying wanted output - javascript

I've written some code to display my favorites in IE8 but for an unknown reason I have no output on the screen despite the fact that my page is accepted by IE and that the test text 'this is a test' is displayed.
my code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />
<script type="text/javascript">
var i = 0;
var favString = "";
var fso;
function GetFavourites(Folder) {
var FavFolder = fso.GetFolder(Folder);
//Gets Favourite Names & URL's for given folder.
var files = new Enumerator(FavFolder.Files);
for (; !files.atEnd(); files.moveNext()) {
var fil = files.item();
if (fil.Type == "Internet Shortcut") {
var textReader = fso.OpenTextFile(fil.Path, 1, false, -2);
var favtext = textReader.ReadAll();
var start = favtext.indexOf("URL", 16);
var stop = favtext.indexOf("\n", start);
favString += fil.Name.replace(/.url/, "");
favString += ":URL:";
//to separate favourite name & favorite URL
favString += favtext.substring(start + 4, stop - 1);
favorites.innerHTML += favString; // Not working !
favorites.innerHTML += 'test'; // Not working too !
favString += ":NEXT:"; //to separate favorites.
i++;
}
}
//Checks any subfolder exists
var subfolders = new Enumerator(FavFolder.SubFolders);
for (; !subfolders.atEnd(); subfolders.moveNext()) {
var folder = subfolders.item();
GetFavourites(folder.Path);
}
}
function Import() {
try {
fso = new ActiveXObject("Scripting.FileSystemObject");
if (fso !== null) {
//Create windows script shell object to access Favorites folder in user system.
var object = new ActiveXObject("WScript.Shell");
var favfolderName = object.SpecialFolders("Favorites");
if (favString === "") {
GetFavourites(favfolderName);
}
}
}
catch (err) {
alert("Security settings to be modified in your browser ");
}
}
</script>
</head>
<body onload="Import()">
<p>this is a test</p> <!-- Working ! -->
<div id="favorites">
</div>
</body>
</html>

The following works for me:
var fso, favs = [];
function GetFavourites(Folder) {
var FavFolder = fso.GetFolder(Folder);
//Gets Favourite Names & URL's for given folder.
var files = new Enumerator(FavFolder.Files);
for (; !files.atEnd(); files.moveNext()) {
var fil = files.item();
if (fil.Type == "Internet Shortcut") {
var textReader = fso.OpenTextFile(fil.Path, 1, false, -2);
var favtext = textReader.ReadAll();
var start = favtext.indexOf("URL", 16);
var stop = favtext.indexOf("\n", start);
favString = fil.Name.replace(/.url/, "");
favString += ":URL:";
//to separate favourite name & favorite URL
favString += favtext.substring(start + 4, stop - 1);
favs.push(favString);
}
}
//Checks any subfolder exists
var subfolders = new Enumerator(FavFolder.SubFolders);
for (; !subfolders.atEnd(); subfolders.moveNext()) {
var folder = subfolders.item();
GetFavourites(folder.Path);
}
}
function Import() {
try {
fso = new ActiveXObject("Scripting.FileSystemObject");
if (fso !== null) {
//Create windows script shell object to access Favorites folder in user system.
var object = new ActiveXObject("WScript.Shell");
var favfolderName = object.SpecialFolders("Favorites");
if (favString === "") {
GetFavourites(favfolderName);
}
}
}
catch (err) {
alert("Security settings to be modified in your browser ");
}
}
Note that all I changed was the output from an element to an array named favs. I also removed the i variable, because it wasn't used. After running the script, I checked the array in the developer tools console and it contained all my favourites.

If you're getting no output at all, then either fso is null in the Import method or files.AtEnd() always evaluates to false. Since you're focusing on IE here, you might consider placing alert methods in various places with values to debug (such as alert(fso);) throughout your expected code path.

Related

List file names during run time from App script HTML

I have created an app script to get list of all files available in Gdrive. While executing I m unable to pass the file names which are generated during the execution to tag.
My goal is to list the file names which are generated to be populated in HTML
Code.gs
var gSheetName;
var sheet = SpreadsheetApp.openById('1XyZ2m_knnyM7cLN-DtLcHyLX0pKOt5uASCcV8');
var sheets= sheet.getSheetByName('FileList');
var Fname, CountofFiles;
var sessionuser = Session.getActiveUser().getEmail();
function doGet(e) {
return HtmlService.createTemplateFromFile('params').evaluate();
}
function Start() {
try {
gSheetName=sheet.getId();
listFolders(DriveApp.getRootFolder());
return Fname;
}
catch(error) { return error.toString();}
}
function listFolders(folder) {
var folder = folder || DriveApp.getRootFolder();
var files = folder.getFiles();
var data;
while ( files.hasNext() ) {
var file1 = files.next();
var file1 = file1.getId();
var file=DriveApp.getFileById(file1);
var value = Math.floor((file.getLastUpdated()-file.getDateCreated())/(24*3600*1000));
var value1;
var emailid = Session.getActiveUser().getEmail();
Fname = file.getName(); //I want to list this file name in HTML one by one
fileList(Fname);
data = [
file.getName(),
file.getDateCreated(),
file.getLastUpdated(),
folder.getName(),
folder.getId(),
file.getSize()
];
sheets.appendRow(data);
data=[];
}
var subfolders = folder.getFolders();
while (subfolders.hasNext()) {
listFolders(subfolders.next());
}
}
function fileList(fileName) {
var Fname1 = Fname;
return Fname1;
}
params.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="myForm">
<a class="waves-effect waves-light btn-large" onclick="google.script.run.withSuccessHandler(execute).Start();Showhide();">
<i class="material-icons left">cloud</i> Execute
</a>
</form>
<div id="output" style="display:none">
<p>Please wait while we are extracting records...</p>
<img src="https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif">
</div>
<div id="Flist"></div>
<script>
function execute(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('Flist').innerHTML = execute();
document.getElementById('output').innerHTML = 'Completed';
}
function Showhide() {
var x = document.getElementById("output");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
I Need to display list of files which are generated by "Fname = file.getName();" this is where the file names are stored to the variable Fname. Is there a way i can populate these file names in HTML. I tried logging the records which is giving me the names in log but unfortunately i m unable to list in HTML tag. Please help me to solve this.
When you use google.script.run.withSuccessHandler(function) and the server function returns a value, the API passes the value to the new function as a parameter.
Which means when you call google.script.run.withSuccessHandler(execute).Start(), the return value of your Start() will be passed as an argument in your execute().
I noticed that you are trying to call your execute() to get your Flist here:
function execute(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('Flist').innerHTML = execute();
document.getElementById('output').innerHTML = 'Completed';
}
Sample Code Modification:
(code.gs - modified part only)
var Fname = [], CountofFiles;
function Start() {
try {
gSheetName=sheet.getId();
//Clear sheet
sheets.clear();
listFolders(DriveApp.getRootFolder());
return Fname;
}
catch(error) { return error.toString();}
}
function listFolders(folder) {
var folder = folder || DriveApp.getRootFolder();
var files = folder.getFiles();
var data;
while ( files.hasNext() ) {
var file1 = files.next();
var file1 = file1.getId();
var file=DriveApp.getFileById(file1);
var value = Math.floor((file.getLastUpdated()-file.getDateCreated())/(24*3600*1000));
var value1;
var emailid = Session.getActiveUser().getEmail();
//var fileFname = file.getName(); //I want to list this file name in HTML one by one
//fileList(file.getName());
Fname.push(file.getName());
data = [
file.getName(),
file.getDateCreated(),
file.getLastUpdated(),
folder.getName(),
folder.getId(),
file.getSize()
];
sheets.appendRow(data);
data=[];
}
var subfolders = folder.getFolders();
while (subfolders.hasNext()) {
listFolders(subfolders.next());
}
}
(params.html - modified part only)
function execute(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('Flist').innerHTML = status;
document.getElementById('output').innerHTML = 'Completed';
}
Changes done:
Clear FileList sheet every time you click Execute in your html page
I changed Fname to an array and push all file names found.
The array of file names returned by Start() will be passed as argument in your execute(status) hence you can access that in your status variable.
Output:

How to fix "MasterPage is undefined" in javascript function?

I am currently supporting a web-based app in asp.net vb. This part of code below is for checking the session and automatically logs off the user after the expiration of session. Also, I have a security window that pops up upon the successful log in and also logs off the user whenever this pop up window is refreshed or closed.
The problem is I am having an error saying "MasterPage is Undefined" whenever the javascript is calling the functions in MasterPage.master.vb. The error occurs on code MasterPage.LogOn(), MasterPage.GetClientSession(), and the likes.
Below is my javascript in the MasterPage.master file and the functions LogOn(), GetClientSession() and others are on the MasterPage.master.vb file.
This issue only occurs upon the deployment of the system on the test server, and works fine on my local pc.
Anyone who can help please. Thanks so much.
<script type="text/javascript" language="JavaScript">
var SessionTime = 0;
var uname = "";
var status = "";
var clientSession = 0;
var spyOn;
function logon()
{
MasterPage.LogOn();
clientSession = MasterPage.GetClientSession().value;
spyOn = MasterPage.spyOn().value;
setTimeout("CheckSession()", 60000);
if (!spyOn)
{
var spyWin = open('spy.aspx','UserSecurity','width=250,height=100,left=2000,top=2000,status=0,scrollbar=no,titlebar=no,toolbar=no');
}
}
function CheckSession()
{
SessionTime = SessionTime + 1;
if (SessionTime >= clientSession)
{
var uname = document.getElementById("ctl00_hdnUser").value;
var status = document.getElementById("ctl00_hdnStatus").value;
var x = MasterPage.SessionEnded(uname, status).value;
alert(x);
window.open("Login.aspx","_self");
}
setTimeout("CheckSession()", 60000);
}
function RorC()
{
var top=self.screenTop;
if (top>9000)
{
window.location.href="logout.aspx" ;
}
}
function LogMeOut()
{
window.location.href="logout.aspx" ;
}
function ShowTime()
{
var dt = new Date();
document.getElementById("<%= Textbox1.ClientID %>").value = dt.toLocaleTimeString();
window.setTimeout("ShowTime()", 1000);
MasterPage.CheckSession(CheckSession_CallBack);
}
window.setTimeout("ShowTime()", 1000);
function CheckSession_CallBack(response)
{
var ret = response.value;
if (ret == "")
{
isClose = true;
window.location.href="login.aspx"
}
}
</script>
This can be fixed by adding handlers (<httphandlers> under <system.web> section and <handlers> under <system.webserver> section) on web.config that supports IIS7 and also setting the application pool on IIS manager from "Integrated" to "Classic".

File downloading function takes more than 6 minutes, how can I improve it, in google app script?

My file downloading function takes more than 6 minutes. Therefore, I couldn't download the whole files. Is there anyway to complete the download within 6 minutes? Or any other solution ?
Html
<html>
<form id="downloadpdf">
<input id="urlclass" type="text" name="urlname" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var urllink = []; //this value assigned by another function. But let us assign statics variable as example urllink={“url1,url2,url3”}
$(document).ready(function() {
$("#downloadpdf").submit(function() {
$("#urlclass").val(urllink);
google.script.run.withSuccessHandler(function(retsearch){
}).downloadthefile(this);
});
});
</script>
</html>
code.gs
function downloadthefile(urlpass) {
var timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
var now = Utilities.formatDate(new Date(),timezone, "EEE MMM d yyyy HH:mm:ss");
var dest_folder = DriveApp.createFolder(now);
var dest_folder_id = DriveApp.getFoldersByName(dest_folder).next().getId();
var source_folder = DriveApp.getFolderById(“the source folder id");
var dest_folder = DriveApp.getFolderById(dest_folder_id );
// The url that is passed to the function as string
var urlstring = urlpass.urlname;
// Make array of url
var resultarray = urlstring.split(',');
for(var i=0; i < resultarray.length; i++){
var fileurl = resultarray[i];
// Retrieve the url Id
var fileid = fileurl.match(/[-\w]{25,}/);
var file = DriveApp.getFileById(fileid);
var filecopy = file.makeCopy(file.getName());
dest_folder.addFile(filecopy);
}
}
Workaround for not hitting Google Apps Script execution time limit is to run copy requests in your modal window code (plain JavaScript with XHR requests to Google Drive API) instead of doing it in GAS script.
Edited [adapted for Deploy as web app]:
Code.gs:
function doGet(){
var template = HtmlService.createTemplateFromFile('copyDriveFiles')
// need to have next line of text somewhere (even commented out) to trigger correct scopes for script and token:
// DriveApp.getFiles() // <- DO NOT DELETE THIS COMMENT
// pass token
template.data = {
token: ScriptApp.getOAuthToken()
};
var html = template.evaluate().setTitle('Download');
return html;
}
copyDriveFiles.html:
<html>
<head>
</head>
<body>
<form id="downloadform">
<input id="downloadpdf" type="submit" value="download">
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
// this value assigned by another function. But let us assign statics variable as example urllink = '{“url1,url2,url3”}'
var urllink = 'https://docs.google.com/document/d/XXXXXX/edit,https://docs.google.com/document/d/ZZZZZZ/edit';
// download files
$(document).ready(function(){
$("#downloadform").submit(function(e){
downloadFiles(urllink);
return false;
});
});
function downloadFiles(urllink)
{
<?
// create destination folder
var timezone = Session.getScriptTimeZone();
var now = Utilities.formatDate(new Date(), timezone, "EEE MMM d yyyy HH:mm:ss");
var folder = DriveApp.createFolder(now);
var folderId = folder.getId();
?>
// get folder id
var folderId = <?=folderId?>;
var resultArray = urllink.split(',');
// loop file urls
for (var i = 0; i < resultArray.length; i++)
{
// retrieve the file id from url
var fileId = resultArray[i].match(/[-\w]{25,}/);
// copy file to folder
copyFileToFolder(fileId, folderId);
}
}
function copyFileToFolder(fileId, folderId)
{
var xhr = new XMLHttpRequest();
// request payload - set parents
// here you can specify file name etc: https://developers.google.com/drive/v3/reference/files/copy
var requestBody = {
parents: [folderId]
};
xhr.open('POST', 'https://www.googleapis.com/drive/v3/files/'+fileId+'/copy');
xhr.setRequestHeader('Authorization', 'Bearer <?=data.token?>');
xhr.setRequestHeader('Content-type', 'application/json');
// send request
xhr.send(JSON.stringify(requestBody));
}
</script>
</body>
</html>
Result:

Unable to receive parameter in query string when redirected to other page

Hi I am developing one application in java-script. I have two pages default.aspx and addnewitem.aspx. there is one html table in default.aspx and one button. When i click on button i want to redirect to addnewitem.aspx page. I have some parameters to send in query string. I am able to redirect to addnewitem.aspx but page not found error i am getting. I am not sure why i am getting page not found error. I am trying as below.
function getValues() {
var Title = "dfd";
var PrimarySkills = "fdfd";
var SecondarySkills = "dfdf";
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=" + encodeURIComponent($(Title)) + "&PrimarySkills=" + encodeURIComponent($(PrimarySkills)) + "&SecondarySkills=" + encodeURIComponent($(SecondarySkills));
window.location.href = url;
}
I am checking querystring in addnewitem.aspx as below.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["Title"] != null && queryString["PrimarySkills"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Title:</b> " + queryString["Title"] + " <b>PrimarySkills:</b> " + queryString["PrimarySkills"] + " <b>SecondarySkills:</b> " + queryString["SecondarySkills"];
$("#lblData").html(data);
alert(data);
}
});
</script>
"http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=%5Bobject%20Object%5D&PrimarySkills=%5Bobject%20Object%5D&SecondarySkills=%5Bobject%20Object%5D"
I tried lot to fix this. May i know where i am doing wrong? Thanks for your help.
You should use the relative path in your url instead of hard coding the entire folder structure, which is probably incorrect since you are getting a 404. And you need to change the url every time you publish the site to the hosting enviroment when you hard code it like that.
So change
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=...
into
var url = "/AddNewItem.aspx?Title=...
if both the pages are in the same folder. Should AddNewItem.aspx be located in the Pages folder, you have to add that folder of course: var url = "/Pages/AddNewItem.aspx?Title=...

xpages JSON-RPC Service handling response from callback funciton

I have a slickgrid screen (on regular Domino form) wherein user can select and update some documents. I needed to show a pop-up displaying status of every selected document so I created an XPage. In my XPage I am looping through selected documents array (json) and call an RPC method for every document. Code to call RPC method is in a button which is clicked on onClientLoad event of XPAGE. RPC is working fine because documents are being updated as desired. Earlier I had RPC return HTML code for row () which was being appended to HTML table. It works in Firefox but not in IE. Now I am trying to append rows using Dojo but that’s not working either.
Here is my Javascript code on button click.
var reassign = window.opener.document.getElementById("ResUsera").innerHTML;
var arr = new Array();
var grid = window.opener.gGrid;
var selRows = grid.getSelectedRows();
for (k=0;k<selRows.length;k++)
{
arr.push(grid.getDataItem(selRows[k]));
}
var tab = dojo.byId("view:_id1:resTable");
while (arr.length > 0)
{
var fldList = new Array();
var ukey;
var db;
var reqStatusArr = new Array();
var docType;
var docno;
ukey = arr[0].ukey;
db = arr[0].docdb;
docType = arr[0].doctypeonly;
docno = arr[0].docnum;
fldList.push(arr[0].fldIndex);
reqStatusArr.push(arr[0].reqstatusonly);
arr.splice(0,1)
for (i=0;i < arr.length && arr.length>0;i++)
{
if ((ukey == arr[i].ukey) && (db == arr[i].docdb))
{
fldList.push(arr[i].fldIndex);
reqStatusArr.push(arr[i].reqstatusonly);
arr.splice(i,1);
i--;
}
}
console.log(ukey+" - "+db+" - "+docno+" - "+docType);
var rmcall = faUpdate.updateAssignments(db,ukey,fldList,reassign);
rmcall.addCallback(function(response)
{
require(["dojo/html","dojo/dom","dojo/domReady!"],function(html,dom)
{
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
html.set(tbdy,
tbdy.innerHTML+"<tr>"+
"<td>"+docType+"</td>"+
"<td>"+docno+"</td>"+
"<td>"+reqStatusArr.join("</br>")+"</td>"+
"<td>"+response+"</td></tr>"
);
});
});
}
dojo.byId("view:_id1:resTable").style.display="inline";
dojo.byId("idLoad").style.display="none";
RPC Service Code
<xe:jsonRpcService
id="jsonRpcService2"
serviceName="faUpdate">
<xe:this.methods>
<xe:remoteMethod name="updateAssignments">
<xe:this.arguments>
<xe:remoteMethodArg
name="dbPth"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="uniquekey"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="fieldList"
type="list">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="reassignee"
type="string">
</xe:remoteMethodArg>
</xe:this.arguments>
<xe:this.script><![CDATA[print ("starting update assignments from future assignments page");
var db:NotesDatabase = null;
var vw:NotesView = null;
var doc:NotesDocument = null;
try{
db=session.getDatabase("",dbPth);
if (null!= db){
print(db.getFileName());
vw = db.getView("DocUniqueKey");
if (null!=vw){
print ("got the view");
doc = vw.getDocumentByKey(uniquekey);
if (null!=doc)
{
//check if the document is not locked
if (doc.getItemValueString("DocLockUser")=="")
{
print ("Got the document");
for (i=0;i<fieldList.length;i++)
{
print (fieldList[i]);
doc.replaceItemValue(fieldList[i],reassignee);
}
doc.save(true);
return "SUCCESS";
}
else
{
return "FAIL - document locked by "+session.createName(doc.getItemValueString("DocLockUser")).getCommon();
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 0";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 1";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 2";
}
}
catch(e){
print ("Exception occured --> "+ e.toString());
return "FAIL - Contact IT Deptt - Code: 3";
}
finally{
if (null!=doc){
doc.recycle();
vw.recycle();
db.recycle();
}
}]]></xe:this.script>
</xe:remoteMethod>
</xe:this.methods>
</xe:jsonRpcService>
Thanks in advance
I have resolved this issue. First, CSJS variables were not reliably set in callback function so I made RPC return the HTML string I wanted. Second was my mistake in CSJS. I was trying to fetch tbody from table using
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
where as it returns an array so it should have been
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName**("tbody")[0]**;
also I moved tbody above while loop. I can post entire code if anyone is interested!!

Categories

Resources