- I have replaced to fragile text-searching with XML parsing from the built-in XML library. What is not apparent from the documentation (and what makes XML parsing practical using this library) is that apart from the defined methods you can use dot notation for DOM navigation.
myXmlElement.html.body.div.p.getText()
- I parameterised the getGRCPassword() function call so that it can return any of the password options shown on the GRC password generation page. They types are Hex, ASCII and Alphanumeric.
I have also published my Get GRC Password Google Spreadsheet in case anyone is interested. The full source code for my getGRCPassword function is below:
/* This is a function which will return a new alphamnumeric only password from GRC.com.
* @param passwordType: Type of password to return (1=HEX, 2=ASCII, 3=Alpha Numeric)
* @returns: The requested password
*/
function getGrcPassword(passwordType) {
var sPasswordPageAddr = 'https://www.grc.com/passwords.htm';
//@todo: Remove redundant error checking and catching done for the request.
//check arguments
if(!passwordType) {
passwordType = 3;
} else if(passwordType.constructor.name != 'Number' || passwordType < 1 || passwordType >3) {
return '#ERROR: Bad argument. PasswordType, if provided, must be 1,2 or 3';
}
//get content of password page
try {
var response = UrlFetchApp.fetch(sPasswordPageAddr);
} catch(e) { return '#ERROR: ' + e.message; }
//Examine response and extract password
//check to see if page received successfully:
if(response.getResponseCode() == 200) {
//if received successfully, examine the content and look for the places we expect the password to be
try {
var responseXml = Xml.parse(response.getContentText(), true);
var sPassword = responseXml.html.body.getElements('center')[0].getElements('center')[passwordType].table.tr.td.table.tr.td.font.getText();
return sPassword;
} catch(e) {
//We could not find the password preamble. Maybe the page has changed?
//Browser.msgBox('Could not find password string. Page structure might have changed');
return '#ERROR: Could not find password string. Page structure might have changed';
}
} else {
//bad response from webserver. Maybe our address is wrong.
//Maybe their webserver is down, etc
//Browser.msgBox('Problem accessing ' + sPasswordPageAddr
// + ': Response code ' + response.getResponseCode());
return '#ERROR: Problem accessing ' + sPasswordPageAddr
+ ': Response code ' + response.getResponseCode();
}
}
No comments:
Post a Comment