Codeigniter Auto completion is not working - javascript

Hello Auto completion is not working well in my application.When we type a name it displays only a blank list[ Screenshots attached ].
Controller Code
public function list_UserByName($letters)
{
if(strpos($letters, ","))
{
$letters1 = explode(",",$letters);
$lecount = count($letters1);
$letters = $letters1[$lecount-1];
}
$letters = preg_replace("/[^a-z0-9 ]/si","",$letters);
$response=$this->user_model->getAutoUserList($letters);
}
Model Code
public function getAutoUserList($letters)
{
$letters = preg_replace("/[^a-z0-9 ]/si","",$letters);
//AND user_type='C' AND user_status='A'
$query="select * from gm_users where uname Like '%$letters%'";
$result_query =$this->db->query($query);
foreach($result_query->result() as $result)
{
//echo "###".$result."|";
//$pinlevel =$this->functions->get_pinlevel($result->pinLevel);
//echo $result->userId."###".$result->uname." [ ".$pinlevel." ] "."|";
echo $result->userId."###".$result->uname."".$result->address." ".$result->city."|";
}
}
billing.php
<input type="text" autocomplete="off" size="20" name="txtname" id="txtname" onkeyup="ajax_showOptions(this,'getCountriesByLetters',event);" value=""/>
ajax-dynamic-list.js
/************************************************************************************************************
(C) www.dhtmlgoodies.com, April 2006
This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.
Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.
Thank you!
www.dhtmlgoodies.com
Alf Magne Kalleland
************************************************************************************************************/
var ajaxBox_offsetX = 25;
var ajaxBox_offsetY = 5;
var ajax_list_externalFile = site_url+'/catalog/list_UserByName'; // Path to external file
var minimumLettersBeforeLookup = 1; // Number of letters entered before a lookup is performed.
var ajax_list_objects = new Array();
var ajax_list_cachedLists = new Array();
var ajax_list_activeInput = false;
var ajax_list_activeItem;
var ajax_list_optionDivFirstItem = false;
var ajax_list_currentLetters = new Array();
var ajax_optionDiv = false;
var ajax_optionDiv_iframe = false;
var ajax_list_MSIE = false;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)ajax_list_MSIE=true;
var currentListIndex = 0;
function ajax_getTopPos(inputObj)
{
var returnValue = inputObj.offsetTop;
while((inputObj = inputObj.offsetParent) != null){
returnValue += inputObj.offsetTop;
}
return returnValue;
}
function ajax_list_cancelEvent()
{
return false;
}
function ajax_getLeftPos(inputObj)
{
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
return returnValue;
}
// Edited
function ajax_option_setValue_bkp(e,inputObj)
{
if(!inputObj)inputObj=this;
var tmpValue = inputObj.innerHTML;
//alert(inputObj.id);
document.getElementById('saleUserId').value=inputObj.id;
if(ajax_list_MSIE)tmpValue = inputObj.innerText;else tmpValue = inputObj.textContent;
if(!tmpValue)tmpValue = inputObj.innerHTML;
val = ajax_list_activeInput.value.split(',');
vals = '';
count = val.length - 1;
for(i=0;i<count;i++)
{
vals = vals + val[i] + ',';
}
ajax_list_activeInput.value = vals + tmpValue;
if(document.getElementById(ajax_list_activeInput.name + '_hidden'))document.getElementById(ajax_list_activeInput.name + '_hidden').value = inputObj.id;
ajax_options_hide();
}
function ajax_option_setValue(e,inputObj)
{
if(!inputObj)inputObj=this;
var tmpValue = inputObj.innerHTML;
//alert(inputObj.id);
document.getElementById('saleUserId').value=inputObj.id;
if(ajax_list_MSIE)tmpValue = inputObj.innerText;else tmpValue = inputObj.textContent;
if(!tmpValue)tmpValue = inputObj.innerHTML;
ajax_list_activeInput.value = tmpValue;
if(document.getElementById(ajax_list_activeInput.name + '_hidden'))document.getElementById(ajax_list_activeInput.name + '_hidden').value = inputObj.id;
ajax_options_hide();
}
function ajax_options_hide()
{
if(ajax_optionDiv)ajax_optionDiv.style.display='none';
if(ajax_optionDiv_iframe)ajax_optionDiv_iframe.style.display='none';
}
function ajax_options_rollOverActiveItem(item,fromKeyBoard)
{
if(ajax_list_activeItem)ajax_list_activeItem.className='optionDiv';
item.className='optionDivSelected';
ajax_list_activeItem = item;
if(fromKeyBoard){
if(ajax_list_activeItem.offsetTop>ajax_optionDiv.offsetHeight){
ajax_optionDiv.scrollTop = ajax_list_activeItem.offsetTop - ajax_optionDiv.offsetHeight + ajax_list_activeItem.offsetHeight + 2 ;
}
if(ajax_list_activeItem.offsetTop<ajax_optionDiv.scrollTop)
{
ajax_optionDiv.scrollTop = 0;
}
}
}
function ajax_option_list_buildList(letters,paramToExternalFile)
{
ajax_optionDiv.innerHTML = '';
ajax_list_activeItem = false;
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length<=1){
ajax_options_hide();
return;
}
ajax_list_optionDivFirstItem = false;
var optionsAdded = false;
for(var no=0;no<ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length;no++){
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()][no].length==0)continue;
optionsAdded = true;
var div = document.createElement('DIV');
var items = ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()][no].split(/###/gi);
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length==1 && ajax_list_activeInput.value == items[0]){
ajax_options_hide();
return;
}
div.innerHTML = items[items.length-1];
div.id = items[0];
div.className='optionDiv';
div.onmouseover = function(){ ajax_options_rollOverActiveItem(this,false) }
div.onclick = ajax_option_setValue;
if(!ajax_list_optionDivFirstItem)ajax_list_optionDivFirstItem = div;
ajax_optionDiv.appendChild(div);
}
if(optionsAdded){
ajax_optionDiv.style.display='block';
if(ajax_optionDiv_iframe)ajax_optionDiv_iframe.style.display='';
ajax_options_rollOverActiveItem(ajax_list_optionDivFirstItem,true);
}
}
function ajax_option_list_showContent(ajaxIndex,inputObj,paramToExternalFile,whichIndex)
{
if(whichIndex!=currentListIndex)return;
var letters = inputObj.value;
var content = ajax_list_objects[ajaxIndex].response;
var elements = content.split('|');
//alert(content);
ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()] = elements;
ajax_option_list_buildList(letters,paramToExternalFile);
}
function ajax_option_resize(inputObj)
{
ajax_optionDiv.style.top = (ajax_getTopPos(inputObj) + inputObj.offsetHeight + ajaxBox_offsetY) + 'px';
ajax_optionDiv.style.left = (ajax_getLeftPos(inputObj) + ajaxBox_offsetX) + 'px';
if(ajax_optionDiv_iframe){
ajax_optionDiv_iframe.style.left = ajax_optionDiv.style.left;
ajax_optionDiv_iframe.style.top = ajax_optionDiv.style.top;
}
}
function ajax_showOptions(inputObj,paramToExternalFile,e)
{
document.getElementById('saleUserId').value='';
if(e.keyCode==13 || e.keyCode==9)return;
if(ajax_list_currentLetters[inputObj.name]==inputObj.value)return;
if(!ajax_list_cachedLists[paramToExternalFile])ajax_list_cachedLists[paramToExternalFile] = new Array();
ajax_list_currentLetters[inputObj.name] = inputObj.value;
if(!ajax_optionDiv){
ajax_optionDiv = document.createElement('DIV');
ajax_optionDiv.id = 'ajax_listOfOptions';
document.body.appendChild(ajax_optionDiv);
if(ajax_list_MSIE){
ajax_optionDiv_iframe = document.createElement('IFRAME');
ajax_optionDiv_iframe.border='0';
ajax_optionDiv_iframe.style.width = ajax_optionDiv.clientWidth + 'px';
ajax_optionDiv_iframe.style.height = ajax_optionDiv.clientHeight + 'px';
ajax_optionDiv_iframe.id = 'ajax_listOfOptions_iframe';
document.body.appendChild(ajax_optionDiv_iframe);
}
var allInputs = document.getElementsByTagName('INPUT');
for(var no=0;no<allInputs.length;no++){
if(!allInputs[no].onkeyup)allInputs[no].onfocus = ajax_options_hide;
}
var allSelects = document.getElementsByTagName('SELECT');
for(var no=0;no<allSelects.length;no++){
allSelects[no].onfocus = ajax_options_hide;
}
var oldonkeydown=document.body.onkeydown;
if(typeof oldonkeydown!='function'){
document.body.onkeydown=ajax_option_keyNavigation;
}else{
document.body.onkeydown=function(){
oldonkeydown();
ajax_option_keyNavigation() ;}
}
var oldonresize=document.body.onresize;
if(typeof oldonresize!='function'){
document.body.onresize=function() {ajax_option_resize(inputObj); };
}else{
document.body.onresize=function(){oldonresize();
ajax_option_resize(inputObj) ;}
}
}
if(inputObj.value.length<minimumLettersBeforeLookup){
ajax_options_hide();
return;
}
ajax_optionDiv.style.top = (ajax_getTopPos(inputObj) + inputObj.offsetHeight + ajaxBox_offsetY) + 'px';
ajax_optionDiv.style.left = (ajax_getLeftPos(inputObj) + ajaxBox_offsetX) + 'px';
if(ajax_optionDiv_iframe){
ajax_optionDiv_iframe.style.left = ajax_optionDiv.style.left;
ajax_optionDiv_iframe.style.top = ajax_optionDiv.style.top;
}
ajax_list_activeInput = inputObj;
ajax_optionDiv.onselectstart = ajax_list_cancelEvent;
currentListIndex++;
if(ajax_list_cachedLists[paramToExternalFile][inputObj.value.toLowerCase()]){
ajax_option_list_buildList(inputObj.value,paramToExternalFile,currentListIndex);
}else{
var tmpIndex=currentListIndex/1;
ajax_optionDiv.innerHTML = '';
var ajaxIndex = ajax_list_objects.length;
ajax_list_objects[ajaxIndex] = new sack();
var search_key = inputObj.value.replace(" ","+");
//search_key1 = search_key.replace(",",",");
var url = ajax_list_externalFile + '/' +search_key;
ajax_list_objects[ajaxIndex].requestFile = url; // Specifying which file to get
ajax_list_objects[ajaxIndex].onCompletion = function(){ ajax_option_list_showContent(ajaxIndex,inputObj,paramToExternalFile,tmpIndex); }; // Specify function that will be executed after file has been found
ajax_list_objects[ajaxIndex].runAJAX(); // Execute AJAX function
}
}
function wordcount(string) {
var a = string.split(/\s+/g); // split the sentence into an array of words
return a.length;
}
function ajax_option_keyNavigation(e)
{
if(document.all)e = event;
if(!ajax_optionDiv)return;
if(ajax_optionDiv.style.display=='none')return;
if(e.keyCode==38){ // Up arrow
if(!ajax_list_activeItem)return;
if(ajax_list_activeItem && !ajax_list_activeItem.previousSibling)return;
ajax_options_rollOverActiveItem(ajax_list_activeItem.previousSibling,true);
}
if(e.keyCode==40){ // Down arrow
if(!ajax_list_activeItem){
ajax_options_rollOverActiveItem(ajax_list_optionDivFirstItem,true);
}else{
if(!ajax_list_activeItem.nextSibling)return;
ajax_options_rollOverActiveItem(ajax_list_activeItem.nextSibling,true);
}
}
/*if(e.keyCode==13 || e.keyCode==9){ // Enter key or tab key
if(ajax_list_activeItem && ajax_list_activeItem.className=='optionDivSelected')ajax_option_setValue(false,ajax_list_activeItem);
if(e.keyCode==13)return false; else return true;
}
if(e.keyCode==27){ // Escape key
ajax_options_hide();
}*/
}
//document.documentElement.onclick = autoHideList;
function autoHideList(e)
{
if(document.all)e = event;
if (e.target) source = e.target;
else if (e.srcElement) source = e.srcElement;
if (source.nodeType == 3) // defeat Safari bug
source = source.parentNode;
if(source.tagName.toLowerCase()!='input' && source.tagName.toLowerCase()!='textarea')ajax_options_hide();
}
Am a beginner in php as well as Codeigniter

Just echo your data in your controller
change
$response=$this->user_model->getAutoUserList($letters);
To
echo $this->user_model->getAutoUserList($letters);

change
onkeyup="ajax_showOptions(this,'getCountriesByLetters',event);
to
onkeyup="ajax_showOptions(this,'list_UserByName',event);
there is a question on this topic on stackoverflow, but an entire different process.
My Codeigniter autocomplete with ajax

Related

Function call within a function not working

I have a function I call to initialize a page :
function initialize_selections() {
var freeamountElement = document.getElementById("text-freeamount");
var dlyElement = document.getElementById("text-dly");
var freeshipperElement = document.getElementById("text-freeshipper");
if(freeamountElement){
var shippingMethod = document.getElementById("text-freeamount").innerText;
document.getElementById('radio-freeamount').checked = true;
document.getElementById('value-shipping').innerHTML = '$0.00';
document.getElementById('text-shipping').innerHTML = shippingMethod;
}else if(dlyElement){
var shippingMethod = document.getElementById("text-dly").innerText;
document.getElementById('radio-dly').checked = true;
document.getElementById('value-shipping').innerHTML = '$0.00';
document.getElementById('text-shipping').innerHTML = shippingMethod;
}else if(freeshipperElement){
var shippingMethod = document.getElementById("text-freeshipper").innerText;
document.getElementById('radio-freeshipper').checked = true;
document.getElementById('value-shipping').innerHTML = '$0.00';
document.getElementById('text-shipping').innerHTML = shippingMethod;
}else{
var shippingMethod = document.getElementById("text-upsxml").innerText;
var shippingValue = document.getElementById("value-upsxml").innerText;
document.getElementById('radio-upsxml').checked = true;
document.getElementById('value-shipping').innerHTML = shippingValue;
document.getElementById('text-shipping').innerHTML = shippingMethod;
}
// myPoints();
};
This is working well on initial page load. Depending on specfic conditions I want to call it again, from a separate function:
function hideForm(){
if (document.getElementById('thebox').checked==true){
document.getElementById('formdiv').style.display="block";
document.getElementById('formdiv2').style.display="none";
document.getElementById('formdiv3').style.display="block";
var shipping_method = 'Pick Up Your Order';
document.getElementById('text-shipping').innerHTML = shipping_method ;
document.getElementById('value-shipping').innerHTML = '$0.00';
document.querySelector('input[name="shipping"]:checked').checked = false;
// myPoints();
} else {
document.getElementById('formdiv').style.display="none";
document.getElementById('formdiv2').style.display="block";
document.getElementById('formdiv3').style.display="none";
var shipping_method = document.getElementById('text-upsxml').innerText;
document.getElementById('text-shipping').innerHTML = shipping_method ;
var shipping_value = document.getElementById('value-upsxml').innerText;
document.getElementById('value-shipping').innerHTML = shipping_value;
document.querySelector('input[name="shipping"]:checked').checked = false;
document.querySelector('input[name="payment"]:checked').checked = false;
initialize_selections();
};
};
Both codes work well and do as I am looking for except that I can not call initialize_selections from hideForm (same thing occurs with the myPoints function, but commented it out to isolate the issue.

google docs apps script function calling very slow

I'm writing a google docs apps script in making a google docs add-on. When the user clicks a button in the sidebar, an apps script function is called named executeSpellChecking. This apps script function makes a remote POST call after getting the document's text.
total time = time that takes from when user clicks the button, until the .withSuccessHandler(, that means until executeSpellChecking returns = 2000 ms
function time = time that takes for the executeSpellChecking call to complete from its start to its end = 1400 ms
t3 = time that takes for the remote POST call to be completed = 800ms
t4 = time that takes for the same remote POST call to complete in a VB.NET app = 200ms
Problems:
Why total time to complete is bigger than total function time by a staggering 600ms, what else happens there? shouldn't they be equal? How can I improve it?
Why t3 is bigger than t4 ? Shouldn't they be equal? Is there something wrong with POST requests when happening from .gs? How can I improve it ?
the code is (sidebar.html):
function runSpellChecking() {
gb_IsSpellcheckingRunning = true;
//gb_isAutoCorrecting = false;
gi_CorrectionCurrWordIndex = -1;
$("#btnStartCorr").attr("disabled", true);
$("#divMistakes").html("");
this.disabled = true;
//$('#error').remove();
var origin = $('input[name=origin]:checked').val();
var dest = $('input[name=dest]:checked').val();
var savePrefs = $('#save-prefs').is(':checked');
//var t1 = new Date().getTime();
console.time("total time");
google.script.run
.withSuccessHandler(
function(textAndTranslation, element) {
if (gb_IsSpellCheckingEnabled) {
console.timeEnd("total time");
//var t2 = new Date().getTime();
go_TextAndTranslation = JSON.parse(JSON.stringify(textAndTranslation));
var pagewords = textAndTranslation.pagewords;
var spellchecked = textAndTranslation.spellchecked;
//alert("total time to complete:" + (t2-t1) + "###" + go_TextAndTranslation.time);
//irrelevant code follows below...
}
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.executeSpellChecking(origin, dest, savePrefs);
}
and the called function code is (spellcheck.gs):
function executeSpellChecking(origin, dest, savePrefs) {
//var t1 = new Date().getTime();
console.time("function time");
var body = DocumentApp.getActiveDocument().getBody();
var alltext = body.getText();
var lastchar = alltext.slice(-1);
if (lastchar != " " && lastchar != "\n") {
body.editAsText().insertText(alltext.length, "\n");
alltext = body.getText();
}
var arr_alltext = alltext.split(/[\s\n]/);
var pagewords = new Object;
var pagewordsOrig = new Object;
var pagewordsOrigOffset = new Object;
var offset = 0;
var curWord = "";
var cnt = 0;
for (var i = 0; i < arr_alltext.length; i++) {
curWord = arr_alltext[i];
if (StringHasSimeioStiksis(curWord)) {
curWord = replaceSimeiaStiksis(curWord);
var arr3 = curWord.split(" ");
for (var k = 0; k < arr3.length; k++) {
curWord = arr3[k];
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length;
cnt++;
}
offset++;
} else {
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/\n]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length + 1;
cnt++;
}
}
var respTString = "";
var url = 'https://www.example.org/spellchecker.php';
var data = {
"Text" : JSON.stringify(pagewords),
"idOffset" : "0",
"lexID" : "8",
"userEmail" : "test#example.org"
};
var payload = JSON.stringify(data);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
//var t11 = new Date().getTime();
console.time("POST time");
var response = UrlFetchApp.fetch(url, options);
console.timeEnd("POST time");
//var t22 = new Date().getTime();
var resp = response.getContentText();
respTString = resp;
var spellchecked = JSON.parse(respTString);
var style = {};
for (var k in pagewords){
if (pagewords.hasOwnProperty(k)) {
if (spellchecked.hasOwnProperty(k)) {
if (spellchecked[k].substr(0, 1) == "1") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#000000";
}
if (spellchecked[k].substr(0, 1) == "0") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#FF0000";
}
if (spellchecked[k].substr(0, 1) == "4") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#0000FF";
}
if (pagewordsOrigOffset[k] < alltext.length) {
body.editAsText().setAttributes(pagewordsOrigOffset[k], pagewordsOrigOffset[k] + pagewordsOrig[k].length, style);
}
}
}
}
//var t2 = new Date().getTime();
console.timeEnd("function time")
return {
"pagewords" : pagewords,
"pagewordsOrig" : pagewordsOrig,
"pagewordsOrigOffset" : pagewordsOrigOffset,
"spellchecked" : spellchecked
}
}
Thank you in advance for any help.
EDIT: I updated the code to use console.time according to the suggestion, the results are:
total time: 2048.001953125 ms
Jun 21, 2021, 3:01:40 PM Debug POST time: 809ms
Jun 21, 2021, 3:01:41 PM Debug function time: 1408ms
So the problem is not how time is measured. function time is 1400ms, while the time it takes to return is 2000ms, a difference of 600ms and the POST time is a staggering 800ms, instead of 200ms it takes in VB.net to make the exact same POST call.
Use console.time() and console.timeEnd():
https://developers.google.com/apps-script/reference/base/console
I modified the code for you. console.timeEnd() outputs the time duration in the console automatically, so I removed the alert for you that showed the time difference.
You might want the strings that I used as the parameter as some sort of constant variable, so there are no magic strings used twice. I hope this is of use to you.
function runSpellChecking() {
gb_IsSpellcheckingRunning = true;
//gb_isAutoCorrecting = false;
gi_CorrectionCurrWordIndex = -1;
$("#btnStartCorr").attr("disabled", true);
$("#divMistakes").html("");
this.disabled = true;
//$('#error').remove();
var origin = $('input[name=origin]:checked').val();
var dest = $('input[name=dest]:checked').val();
var savePrefs = $('#save-prefs').is(':checked');
console.time("total time");
google.script.run
.withSuccessHandler(
function(textAndTranslation, element) {
if (gb_IsSpellCheckingEnabled) {
console.timeEnd("total time");
go_TextAndTranslation = JSON.parse(JSON.stringify(textAndTranslation));
var pagewords = textAndTranslation.pagewords;
var spellchecked = textAndTranslation.spellchecked;
//irrelevant code follows below...
}
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.executeSpellChecking(origin, dest, savePrefs);
}
function executeSpellChecking(origin, dest, savePrefs) {
console.time("function time");
var body = DocumentApp.getActiveDocument().getBody();
var alltext = body.getText();
var lastchar = alltext.slice(-1);
if (lastchar != " " && lastchar != "\n") {
body.editAsText().insertText(alltext.length, "\n");
alltext = body.getText();
}
var arr_alltext = alltext.split(/[\s\n]/);
var pagewords = new Object;
var pagewordsOrig = new Object;
var pagewordsOrigOffset = new Object;
var offset = 0;
var curWord = "";
var cnt = 0;
for (var i = 0; i < arr_alltext.length; i++) {
curWord = arr_alltext[i];
if (StringHasSimeioStiksis(curWord)) {
curWord = replaceSimeiaStiksis(curWord);
var arr3 = curWord.split(" ");
for (var k = 0; k < arr3.length; k++) {
curWord = arr3[k];
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length;
cnt++;
}
offset++;
} else {
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/\n]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length + 1;
cnt++;
}
}
var respTString = "";
var url = 'https://www.example.org/spellchecker.php';
var data = {
"Text" : JSON.stringify(pagewords),
"idOffset" : "0",
"lexID" : "8",
"userEmail" : "test#example.org"
};
var payload = JSON.stringify(data);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
console.time("POST time");
var response = UrlFetchApp.fetch(url, options);
console.timeEnd("POST time");
var resp = response.getContentText();
respTString = resp;
var spellchecked = JSON.parse(respTString);
var style = {};
for (var k in pagewords){
if (pagewords.hasOwnProperty(k)) {
if (spellchecked.hasOwnProperty(k)) {
if (spellchecked[k].substr(0, 1) == "1") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#000000";
}
if (spellchecked[k].substr(0, 1) == "0") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#FF0000";
}
if (spellchecked[k].substr(0, 1) == "4") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#0000FF";
}
if (pagewordsOrigOffset[k] < alltext.length) {
body.editAsText().setAttributes(pagewordsOrigOffset[k], pagewordsOrigOffset[k] + pagewordsOrig[k].length, style);
}
}
}
}
console.timeEnd("function time");
return {
"pagewords" : pagewords,
"pagewordsOrig" : pagewordsOrig,
"pagewordsOrigOffset" : pagewordsOrigOffset,
"spellchecked" : spellchecked
}
}

Upload a file to a web page as an attachment using VBA

I have a situation here. My company has a webpage which we use for ticket creation. The user gets the email and he has to create a ticket based on the info in the email. I tried to automate this process however got stuck at uploading the attachment.
When the user click on the attach button, a new pop up opens and my macro looses the control over the pop up.
So currently what am doing is,
Save the email - which needs to be attached.
Copy the path to clip board using a function
run a vb script to paste and enter using send keys with 5 seconds delay
click on the attach button.
So before the macro clicks the attach button, a VBS runs behind to paste and hit enter. So by the time the pop up opens VBS starts and closes the pop up.
I was checking to run the attach function within VB script so that I dont have to click on attach button. But I am not able to reach anywhere. anyone help?
The below are the functions available in the webpage. I dont know which one to run and how.
<script eval="true">/**
* Validate the attachments to see if at least
* one file is attached. Otherwise, show an alert.
*
* #returns {Boolean}
*/
function validateAttachment() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
for (var i = 0; i < fileFields.size(); i++) {
if (fileFields[i] && fileFields[i].value != "") {
setAttachButton(""); //disable
$('please_wait').style.display = "";
return true;
}
}
alert("Choose a file to attach");
return false;
}
/**
* Does the first attachment input field have a value?
* If not, use the grey button and change type of cursor.
* #param value
*/
function setDeleteButton(value) {
var field = $$('.attachmentRow')[0];
var text = field.select('input')[0];
var deleteButton = field.select('a.attachfile-delete img')[0];
if (!text.getValue().empty()) {
deleteButton.setAttribute('src', 'images/icons/kb_no.gif');
deleteButton.up().style.cursor = 'pointer';
} else {
deleteButton.setAttribute('src', 'images/icons/kb_no_disabled.gif');
deleteButton.up().style.cursor = 'default';
}
}
/**
* If the value passed in is an empty string,
* set the button to disabled state, otherwise
* enabled.
*
* #param value
*/
function setAttachButton(value) {
var attachButton = $("attachButton");
if (value == "")
attachButton.disabled = "true";
else
attachButton.disabled = "";
}
/**
* This controls the remove button for all attachments.
* If there are attachments in the list enable the button.
* Else keep disabled.
*
* #param e
*/
function setRemoveButton(e) {
var removeButton = gel("removeButton");
var deletedSysIdsElement = gel("deleted_sys_ids");
var deletedSysIds = new Array();
var deletedString = deletedSysIdsElement.value;
if (deletedString)
deletedSysIds = deletedString.split(";");
var thisId = e.name.substring(7);
if (e.checked) {
removeButton.disabled = "";
deletedSysIds.push(thisId);
} else {
var index = deletedSysIds.indexOf(thisId);
deletedSysIds.splice(index, 1);
// are there any left checked?
var inputs = document.getElementsByTagName("input");
var nonechecked = true;
var i = 0;
while(i < inputs.length && nonechecked) {
if (inputs[i].type == "checkbox" && inputs[i].name.substring(0, 7) == "sys_id_")
if (inputs[i].checked)
nonechecked = false;
i++;
}
if (nonechecked) {
removeButton.disabled = "true";
}
}
deletedSysIds = deletedSysIds.join(";");
deletedSysIdsElement.value = deletedSysIds;
}
function startRemoveAttachments() {
var removeButton = gel("removeButton");
removeButton.disabled = true;
gel('please_wait').style.display = "";
var thisUrl = gel("sysparm_this_url");
thisUrl.value = "attachment_deleted.do?sysparm_domain_restore=false&sysparm_nostack=yes&sysparm_deleted=" + gel("deleted_sys_ids").value;
return true;
}
/**
* Clear and Remove the attachment field that is
* passed in.
*
* #param field_id
*/
function clearAttachmentField(field) {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
fileFields[0].setAttribute('data-position', 'first');
if (fileFields.size() > 1 && (field.readAttribute('data-position') != "first")) {
//check if field you are removing has a 3rd column (does it have an attach button?)
var needToAttachButton;
var attachButton = field.select('td')[2];
if (attachButton)
needToAttachButton = true;
//remove the field
field.remove();
//if you removed a field with a third column, add an attachbutton onto the new "first" field.
if (attachButton) {
var attachButton = new Element('input', {
"type": "submit",
"id": "attachButton",
"disabled": "true",
"value": "Attach" });
var td = new Element('td', {align: 'right'}).update(attachButton);
Element.extend(td);
form.select('.attachmentRow').first().select('td')[1].insert({'after': td});
}
}
else
clearFileField(field.select('td').first().select('input').first());
checkAndSetAttachButton();
}
/**
* Check all attachment input fields. If there is not attachment
* currently, disable the attachment button, else enable it.
*
* #returns
*/
function checkAndSetAttachButton() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
var validFileCount = 0;
for (var i = 0; i < fileFields.size(); i++) {
var field = fileFields[i].select('td').first().select('input').first();
if (field.getValue() != "") {
if (window.File && window.FileReader && window.FileList)
validFileCount += validateSizeandExt(field);
else
validFileCount += 1;
}
}
if (validFileCount == 0)
setAttachButton("");
else
setAttachButton("true");
}
function validateSizeandExt(field) {
var form = $('sys_attachment');
var maxSize = (form.max_size && form.max_size.value) ? form.max_size.value : 0;
var fileTypes = (form.file_types && form.file_types.value) ? form.file_types.value : "";
var files = field.files;
var allowedSize = maxSize * 1048576;
var warningString = "";
var checkJEXL = true;
for (var i = 0; i < files.length; i++) {
if (checkJEXL && isJEXLExpression(files[i].name)) {
warningString += files[i].name + " is an invalid file name.\n";
}
if (files[i].size > allowedSize && allowedSize != 0)
warningString += files[i].name + " is " + getDisplaySize(files[i].size) + ". The maximum file size is " + getDisplaySize(allowedSize) + ".\n";
if (!isValidFileType(files[i], fileTypes))
warningString += files[i].name + " has a prohibited file extension." + "\n";
}
if (warningString != "") {
alert(warningString);
clearFileField(field);
return 0;
}
return 1;
}
function isJEXLExpression(fileName) {
var phaseOneOpening = fileName.indexOf("$" + "{");
var phaseTwoOpening = fileName.indexOf("$" + "[");
if (phaseOneOpening != -1 || phaseTwoOpening != -1) {
return true;
}
return false;
}
function getDisplaySize(sizeInBytes) {
var kilobytes = Math.round(sizeInBytes / 1024);
if (kilobytes < 1)
kilobytes = 1;
var reportSize = kilobytes + "K";
if (kilobytes > 1024)
reportSize = Math.round(kilobytes / 1024) + "MB";
return reportSize;
}
function isValidFileType(file, types) {
var extensions = types || "";
if (extensions != "") {
extensions.toLowerCase();
extensions = extensions.split(",");
var periodIndex = file.name.lastIndexOf(".");
var extension = file.name.substring(periodIndex+1).toLowerCase();
if (extensions.indexOf(extension) == -1)
return false;
}
return true;
}
/**
* Clear a given field's contents.
*
* #param field
* the field element.
*/
function clearFileField(field) {
$(field).clear();
$(field).parentNode.innerHTML = $(field).parentNode.innerHTML;
checkAndSetAttachButton();
}
/**
* If the attachments are uploaded, clear any extra attachment input fields so
* they do not take up as much screen space. Additionally, clear the first field
* and keep it showing.
*/
function clearAttachmentFields() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
for (var i = 0; i < fileFields.size(); i++) {
if (i == 0)
clearFileField(fileFields[0].select('td').first().select('input').first());
if (i > 0)
fileFields[i].remove();
}
checkAndSetAttachButton();
setDeleteButton();
}
// this get called after an attachment is uploaded to update the display
function refreshAttachments(id, fileName, canDelete, createdBy, createdOn, contentType, encryption, iconPath) {
refreshLiveFeedAttachments(id, fileName, contentType, iconPath);
var encryptCheck = gel("encrypt_checkbox");
if (encryptCheck) {
encryptCheck.checked = false;
$('sysparm_encryption_context').value = "";
}
gel("please_wait").style.display = "none";
// if we didn't get an id, we could not read the attachment due to business rules so we're done
if (typeof id == "undefined")
return;
var noAttachments = gel("no_attachments");
if (noAttachments.style.display == "block")
noAttachments.style.display = "none";
// add the new upload to the display
var table = gel("attachment_table_body");
var tr = cel("tr");
var td = cel("td");
td.style.whiteSpace = "nowrap";
td.colspan = "2";
if (canDelete=="true") {
var input = cel("input");
var checkId = "sys_id_" + id;
input.name = checkId;
input.id = checkId;
input.type = "checkbox";
input.onclick = function() {setRemoveButton(gel(checkId));};
td.appendChild(input);
gel("delete_button_span").style.display = "inline";
var text = document.createTextNode(" ");
td.appendChild(text);
input = cel("input");
input.type = "hidden";
input.name = "Name";
input.value = "false";
td.appendChild(input);
}
var attachment_input = cel("input");
attachment_input.className = "attachment_sys_id";
attachment_input.type = "hidden";
attachment_input.id = id;
td.appendChild(attachment_input);
var anchor = cel("a");
anchor.style.marginRight = "4px";
anchor.href = "sys_attachment.do?sys_id=" + id;
anchor.title = "Attached by " + createdBy + " on " + createdOn;
var imgSrc = iconPath;
if (encryption != "") {
anchor.title += ", Encrypted: " + encryption;
imgSrc = "images/icons/attachment_encrypted.gifx";
}
var img = cel("img");
img.src = imgSrc;
img.alt = anchor.title;
anchor.appendChild(img);
var text = $(cel('a'));
getMessage("Download {0}", function(msg) {
text.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
text.href = "sys_attachment.do?sys_id=" + id;
text.onkeydown = function(event){return allowInPlaceEditModification(text, event);};
text.style.marginRight = "5px";
text.style.maxWidth = "75%";
text.style.display = "inline-block";
text.style.overflow = "hidden";
text.style.verticalAlign = "middle";
if ('innerText' in text)
text.innerText = fileName;
else
text.textContent = fileName;
text.setAttribute("data-id", id);
text.inPlaceEdit({
selectOnStart: true,
turnClickEditingOff: true,
onBeforeEdit: function() {
text.lastAriaLabel = text.getAttribute("aria-label");
text.removeAttribute("aria-label");
text.setAttribute("role", "textbox");
},
onEditCancelled: function() {
text.removeAttribute("role");
if (text.lastAriaLabel) {
text.setAttribute("aria-label", text.lastAriaLabel);
}
},
onAfterEdit: function(newName) {
var oldName = this.oldValue;
var ga = new GlideAjax('AttachmentAjax');
ga.addParam('sysparm_type', 'rename');
ga.addParam('sysparm_value', id);
ga.addParam('sysparm_name', newName);
ga.getXML(function(response){
var answer = response.responseXML.documentElement.getAttribute("answer");
if (answer !== '0')
alert(new GwtMessage().getMessage("Renaming attachment {0} to new name {1} is not allowed", oldName, newName));
$$('a[data-id="' + id + '"]').each(function(elem){
if ('innerText' in elem)
elem.innerText = (answer === '0') ? newName : oldName;
else
elem.textContent = (answer === '0') ? newName : oldName;
});
$$('span[data-id="' + id + '"]').each(function(elem){
if ('innerText' in elem)
elem.innerText = (answer === '0') ? newName : oldName;
else
elem.textContent = (answer === '0') ? newName : oldName;
});
/*
This routine updates the attachment in the attachment modal AND the same attachment on the parent form
*/
getMessage(["Download {0}", "View {0}", "Rename {0}"], function(msg) {
var newDownloadText = new GwtMessage().format(msg["Download {0}"], newName);
var newViewText = new GwtMessage().format(msg["View {0}"], newName);
var newRenameText = new GwtMessage().format(msg["Rename {0}"], newName);
console.log(id)
$$('a[data-id="' + id + '"]').each(function(elem){
elem.setAttribute("aria-label", newDownloadText);
})
$$('.view_' + id).each(function(elem){
elem.setAttribute("aria-label", newViewText);
})
$$('.rename_' + id).each(function(elem){
elem.setAttribute("aria-label", newRenameText);
})
})
text.removeAttribute("role");
});
}
});
if (contentType == "text/html")
anchor.target = "_blank";
td.appendChild(anchor);
td.appendChild(text);
var allowRename = gel('ni.show_rename_link').value;
if (allowRename == "true") {
var renameAttachment = $(cel('a'));
renameAttachment.href = "#";
renameAttachment.setAttribute("role", "button");
getMessage("Rename {0}", function(msg) {
renameAttachment.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
renameAttachment.className = 'attachment rename_' + id;
renameAttachment.onclick = function() {
text.beginEdit();
};
renameAttachment.innerHTML = '[rename]';
td.appendChild(renameAttachment);
}
var showView = gel("ni.show_attachment_view").value;
if (showView == "true") {
var blank = document.createTextNode(" ");
tr.appendChild(blank);
var view = cel("a");
view.href = "#";
getMessage("View {0}", function(msg) {
view.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
var newText = document.createTextNode('[view]');
view.appendChild(newText);
view.className = "attachment view_" + id;
if (showPopup == "false")
view.href = "sys_attachment.do?sys_id=" + id + "&view=true";
else
view.onclick = function() {
tearOffAttachment(id)
};
td.appendChild(blank);
td.appendChild(view);
}
var showPopup = gel("ni.show_attachment_popup").value;
tr.appendChild(td);
table.appendChild(tr);
//If a new attachment is added check if attachments are marked for edge encryption before showing the Download all button
if (!edgeEncryptionEnabledForAttachments && hasAttachments()){
gel("download_all_button").style.display = "inline";
}
var form_table_id = "";
if(gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")){
form_table_id = (gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")).value;
}
if(form_table_id && attachmentParentSysId != form_table_id){
CustomEvent.fire('record.attachment.uploaded', {
sysid: id,
name: fileName,
hoverText: anchor.title,
image: imgSrc,
showRename: allowRename,
showView: showView,
showPopup: showPopup
});
}else{
addAttachmentNameToForm(id, fileName, anchor.title, imgSrc, allowRename, showView, showPopup);
}
if (g_accessibility)
alert(fileName + " " + anchor.title);
}
function refreshLiveFeedAttachments(sys_id, fileName, contentType, iconPath) {
var p = gel('live_feed_message_images');
if (!p)
return;
if (!contentType)
return;
if (contentType.indexOf('image') != 0 || contentType.indexOf('image/tif') == 0)
refreshLiveFeedNonImages(p, sys_id, iconPath, fileName);
else
refreshLiveFeedImages(p, sys_id, fileName);
var container = $('live_feed_image_container');
if (container)
container.show();
}
function refreshLiveFeedNonImages(p, sys_id, iconPath, fileName) {
var a = cel('a');
a.onclick = function() {tearOffAttachment(sys_id)};
a.title = fileName;
a.className = "live_feed_attachment_link";
var img = cel('img');
img.src = iconPath;
img.className = 'live_feed_image_thumbnail';
img.setAttribute("data-sys_id", sys_id);
a.appendChild(img);
var span = cel('span');
span.setAttribute('data-id', sys_id);
if ('innerText' in span)
span.innerText = fileName;
else
span.textContet = fileName;
a.appendChild(span);
p.appendChild(a);
p.appendChild(cel('br'));
setTimeout(this.hideLoading.bind(this), 200);
}
function refreshLiveFeedImages(p, sys_id, fileName) {
var imageName = "sys_attachment.do?sys_id=" + sys_id;
var a = cel('a');
a.onclick = function() {tearOffAttachment(sys_id)};
a.title = fileName;
a.className = "live_feed_attachment_link";
var img = cel('img');
img.src = imageName;
img.className = 'live_feed_image_thumbnail';
img.setAttribute("data-sys_id", sys_id);
a.appendChild(img);
p.appendChild(a);
p.appendChild(cel('br'));
setTimeout(this.hideLoading.bind(this), 200);
}
// this get called after attachments are deleted to update the display
function deletedAttachments(sysIds) {
var form_table_id = "";
if(gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")){
form_table_id = (gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")).value;
}
if(form_table_id && attachmentParentSysId != form_table_id){
CustomEvent.fire('record.attachment.deleted', sysIds);
return;
}
deleteLiveFeedAttachments(sysIds);
var modified = $("attachments_modified");
if (modified)
modified.value = "true";
var header_attachment = $('header_attachment');
gel("deleted_sys_ids").value = ""; // there should be none on the list once we return
var idArray = sysIds.split(";");
for (var i=0; i<idArray.length; i++) {
var id = idArray[i];
changeCount(attachmentParentSysId, 'decrease');
var e = gel("sys_id_" + id);
var tr = e.parentNode.parentNode;
rel(tr);
e = gel("attachment_" + id);
if (e)
rel(e);
}
var inputs = document.getElementsByTagName("input");
var anAttachment = false;
var i = 0;
while(i < inputs.length && !anAttachment) {
if (inputs[i].type == "checkbox" && inputs[i].name.substring(0, 7) == "sys_id_")
anAttachment = true;
i++;
}
if (!anAttachment) {
var noAttachments = gel("no_attachments");
noAttachments.style.display = "none";
var removeButton = gel("removeButton");
removeButton.disabled = true;
var downloadAllButton = gel("download_all_button");
downloadAllButton.style.display = "none";
gel('delete_button_span').style.display = "none";
hideObject($("header_attachment_list_label"));
if (header_attachment)
header_attachment.style.height = "auto";
var line = $("header_attachment_line");
if (line) {
line.style.visibility = "hidden";
line.style.display = "none";
}
}
gel("please_wait").style.display = "none";
var more_attachments = $('more_attachments');
if (more_attachments && header_attachment)
if( (computeAttachmentWidth() - 20) >= (header_attachment.getWidth() - more_attachments.getWidth()))
more_attachments.style.display = 'block';
else
more_attachments.style.display = 'none';
}
function deleteLiveFeedAttachments(sysIds) {
var p = $('live_feed_message_images');
if (!p)
return;
if (!p.visible())
return;
idArray = sysIds.split(";");
for (var i=0; i<idArray.length; i++) {
var imgs = p.select("img.live_feed_image_thumbnail");
if (imgs.length < 1)
return;
for (var j=0; j<imgs.length; j++) {
if (imgs[j].getAttribute("data-sys_id") == idArray[i]) {
var elem = imgs[j].up("a.live_feed_attachment_link");
elem.remove();
if (elem.next() && (elem.next().tagName.toLowerCase() == "br"))
elem.next().remove();
}
}
}
if (p.select("img.live_feed_image_thumbnail").length > 0)
return;
var container = $('live_feed_image_container');
if (container)
container.hide();
}
function computeAttachmentWidth() {
var temp = $('header_attachment_list').select('li');
var totalWidth = 0;
for (var i = 0; i < temp.length; i++) {
totalWidth += temp[i].getWidth();
}
return totalWidth;
}
function closeAttachmentWindow() {
GlideModal.prototype.get('attachment').destroy();
}
/**
* Add an input field to the file browser in the dialog.
* This is called when the "Add Another Attachment" button
* is clicked.
* */
function addRowToTable() {
var formRows = $('sys_attachment').select(".attachmentRow");
var input = "<input type='file' title='Attach' " +
"name='attachFile' onchange='checkAndSetAttachButton(); setDeleteButton(this.value);'" +
"size=41 multiple=true />";
var img = "<a href='#' onclick='clearAttachmentField($(this).up().up()); setDeleteButton(this.value);'>" +
"<img src='images/icons/kb_no.gif'/></a>";
var row = "<tr class='attachmentRow'><td> "
+ input + "</td><td align='right'>" + img + "</td></tr>";
formRows.last().insert({ "after" : row });
}
/**
* Download all attachments
*/
function downloadAllAttachments(){
var downloadUrl = window.location.protocol + '//' + window.location.host + '/download_all_attachments.do?sysparm_sys_id=' + attachmentParentSysId;
window.location = downloadUrl;
}
function hasAttachments(){
return document.getElementsByClassName("attachment_sys_id").length > 0;
}</script>
This is what happens when I click on the attach button in the HTML. attachFile is the ID which I am using in my code to run.
<tr class="attachmentRow">
<td id="attachFileCell" colspan="3">
<input name="attachFile" title="" id="attachFile" onchange="checkAndSetAttachButton(); setDeleteButton(this.value); $('attachButton').click();" type="file" size="41" multiple="true" data-original-title="Attach">
<a class="attachfile-delete" style="display: none; cursor: default;" onclick="clearAttachmentField($(this).up().up()); setDeleteButton(this.value);" href="#">
<img src="images/icons/kb_no_disabled.gif">
</a>
<input disabled="" class="attachfile-attach button" id="attachButton" style="display: none;" type="submit" value="Attach">
</td>
</tr>
This is my VBA Code which I used.
Set IE = New SHDocVw.InternetExplorer
IE.Visible = True
IE.Navigate "https://sorry cant share the link as per the company policy"
Do While IE.Busy = True Or IE.READYSTATE <> 4: DoEvents: Loop
Set HTMLDoc = IE.Document
'***************** Save Email
eachitem.SaveAs StrFile, 3
'***************** file link to clipboard
CopyText StrFile
'***************** Attach Email
HTMLDoc.getElementById("header_add_attachment").Click
Application.Wait (Now() + TimeValue("00:00:02"))
'***************** Call external VBS file to handle the pop up then attach
Shell "Explorer.exe " & StrFolderPath & "SNOW.vbs", vbNormalFocus
HTMLDoc.getElementById("attachFile").Click
SendKeys "{Enter}", True
I tried the below method to call the function, but reaching nowhere! Any assistance would be appreciated. I really dont know which function attaches the file to the website and how.
Set HTMLDoc1 = IE.Document.parentWindow
HTMLDoc1.execScript code:="isJEXLExpression(" & StrFile & ")"
HTMLDoc1.execScript code:="checkAndSetAttachButton()"
HTMLDoc1.execScript code:="setDeleteButton(this.value)"
HTMLDoc1.execScript code:="$('attachButton').click()"
HTMLDoc1.execScript code:="clearAttachmentField($(this).up().up()); setDeleteButton(this.value);"

Why isn't my JavaScript saving data locally?

I try to have my game save, but it doesn't. When it does save, the program lags and resets. I want the game to save the player's $$$, XP, swag, and multiplier bonus. I have called my advisors, they cannot help the situation. I have been fidling with local data save and nothing will seem to work.
sad.png
cloud1.gif
//variables and stuff
var button = document.getElementById("mir");
var walletDisp = document.getElementById("walletDisp");
var xpDisp = document.getElementById("xplabel");
var test = document.getElementById("test");
var upgradeCashButton = document.getElementById("updaCash");
var upgradeCloudButton = document.getElementById("updaCloud");
var cloudLevelMax = 298123019;
var bonus = 100000;
var bonusCount = 2139871;
var wallet = 234018933098452034985;
var cashPerClick = 10000;
var xp = 132412341;
var cloudLevel = 320948;
var sad = true;
var aNiceTimer=setInterval(function(){myTimer()},1000);
//the "get her going" script
button.addEventListener("click", makeItRain, false);
upgradeCashButton.addEventListener("click",upgradeCash, false);
upgradeCloudButton.addEventListener("click",upgradeCloud, false);
xpDisp.addEventListener("click",credits, false);
window.onload = doInit();
chrome.runtime.onInstalled.addListener(function(details){
if(xp=="undefined"){
saveUs();
}
save();
});
function myTimer() {
if(sad===false){if(clicked===false){
document.body.style.backgroundImage="url('res/sad.jpg')";
sad = true;
bonus =1;
bonusCount = 0;
updateOutput();
}}
if(clicked){
bonusCount = bonusCount +.7;
}
if(bonusCount>bonus){
bonus = bonus+1;
bonusCount = 0;
updateOutput();
}
clicked = false;
}
function makeItRain(){
if(isNaN(wallet)){
saveUs();
}
wallet = wallet+cashPerClick*bonus;
if(sad===true){updateBackground();}
sad = false;
clicked = true;
xp = xp+bonus;
updateOutput();
}
function updateOutput(){
xpDisp.innerHTML = "Level "+ Math.round(Math.log(xp) / Math.log(10));
walletDisp.innerHTML = dispNumb(wallet)+"$";
upgradeCashButton.innerHTML = "Up to " +(dispNumb(getCashUpgrade())) +
" for "+ dispNumb(costOfCashUpgrade())+ "$";
upgradeCloudButton.innerHTML = "Add Swag? "+dispNumb(costOfCloudUpgrade())+"$";
if(clicked===true){
button.innerHTML = "Bonus: x "+ bonus;
}else{
button.innerHTML = "Rain those $$$";
}
if(wallet>=costOfCashUpgrade()){
upgradeCashButton.style.background='#6fae3c';
upgradeCashButton.style.border='3px solid #5f9e2c';
}else{
upgradeCashButton.style.background='#FA5858';
upgradeCashButton.style.border='3px solid #FE2E2E';
}
if(wallet>=costOfCloudUpgrade()){
upgradeCloudButton.style.background='#6fae3c';
upgradeCloudButton.style.border='3px solid #5f9e2c';
}else{
upgradeCloudButton.style.background='#FA5858';
upgradeCloudButton.style.border='3px solid #FE2E2E';
}
save();
}
function upgradeCash(){
if(wallet<costOfCashUpgrade()){
return;
}
wallet = wallet - costOfCashUpgrade();
cashPerClick = getCashUpgrade();
xp = xp+costOfCashUpgrade();
updateOutput();
}
function upgradeCloud(){
if(wallet<costOfCloudUpgrade()){
return;
}
if(cloudLevel==cloudLevelMax){
window.location='STOP.html';
return;
}
wallet = wallet - costOfCloudUpgrade();
cloudLevel = cloudLevel+1;
xp = xp+costOfCloudUpgrade();
updateBackground();
sad = false;
updateOutput();
}
function getCashUpgrade(){
numb = cashPerClick;
if(numb<10){
return numb+1;
}
var first = String(numb).charAt(0);
if(first=="1"){
first = "2";
}else if(first=="2"){
first = "5";
}else if(first=="5"){
first = "10";
}
var rest = String(numb).substring(1,String(numb).length);
return parseInt( first+""+rest);
}
function dispNumb(number){
var long = String(number).length;
var temp = 0;
var ending = "hi";
if(long<4){
return number;
}
if(long<7){
temp = Math.round(number/10)/100;
ending = "K";
}else if(long<10){
temp = Math.round(number/10000)/100;
ending = "M";
}else if(long<13){
temp = Math.round(number/10000000)/100;
ending = "B";
}else if(long<16){
temp = Math.round(number/10000000000)/100;
ending = "T";
}
temp = parseFloat(temp).toFixed(2);
return temp + " " +ending;
}
function costOfCashUpgrade(){
return Math.round(4*Math.round(10*cashPerClick*Math.log(cashPerClick)*Math.log(cashPerClick)))+1;
}
function updateBackground(){
document.body.style.backgroundImage="url('res/cloud"+cloudLevel+".gif')";
}
function costOfCloudUpgrade(){
return Math.round(10*Math.pow(4+cloudLevel,cloudLevel+3));
}
function save(){
chrome.storage.local.set({"wallet": wallet});
chrome.storage.local.set({"cashPerClick": cashPerClick});
chrome.storage.local.set({"xp": xp});
chrome.storage.local.set({"cloudLevel": cloudLevel});
}
function load(){
chrome.storage.local.get("wallet", function(item){
wallet = item["wallet"];
});
chrome.storage.local.get("cashPerClick", function(item){
cashPerClick = item["cashPerClick"];
});
chrome.storage.local.get("xp", function(item){
xp = item["xp"];
});
chrome.storage.local.get("cloudLevel", function(item){
cloudLevel = item["cloudLevel"];
});
}
function becomeOneWithWorld(){
var walB = 0;
var cpcB = 0;
var xpB = 0;
var clB = 0;
chrome.storage.sync.get("wallet", function(item){
walB = item["wallet"];
});
chrome.storage.sync.get("cashPerClick", function(item){
cpcB = item["cashPerClick"];
});
chrome.storage.sync.get("cloudLevel", function(item){
clB = item["cloudLevel"];
});
chrome.storage.sync.get("xp", function(item){
xpB = item["xp"];
});
setTimeout(function () {
if(xp>xpB){
chrome.storage.sync.set({"wallet": wallet});
chrome.storage.sync.set({"cashPerClick": cashPerClick});
chrome.storage.sync.set({"xp": xp});
chrome.storage.sync.set({"cloudLevel": cloudLevel});
}else{
chrome.storage.local.set({"wallet": walB});
chrome.storage.local.set({"cashPerClick": cpcB});
chrome.storage.local.set({"xp": xpB});
chrome.storage.local.set({"cloudLevel": clB});
}
load();
}, 100);
}
function saveUs(){
wallet = 0;
cashPerClick = 1;
xp = 1;
cloudLevel = 1;
}
function credits(){
window.location='credit.html';
}
function doInit(){
load();
becomeOneWithWorld();
}
You're using the wrong APIs. The chrome.storage and chrome.runtime APIs are for Chrome extensions, not web sites.
To store data using Javascript in a web page, use the LocalStorage API.

Having an XML xlink in my page causes a JS error - TypeError... ...is not a function

I'm integrating a widget into my page (Houzz). It works, but only if I remove all xlinks in my SVGs. If there are any xlinks, I get the error:
TypeError: elem.className.split is not a function
The SVG is:
<svg version="1.1" id="Layer_4_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="1309.016px" height="634.008px" viewBox="0 0 1309.016 634.008" enable-background="new 0 0 1309.016 634.008"
xml:space="preserve" class="js-animate" style="max-width: 100%;">
<a xlink:type="simple" xlink:href="/meet-the-team"></a>
</svg>
The script is:
(function(d,s,id){if(!d.getElementById(id)){var js=d.createElement(s);js.id=id;js.async=true;js.src="//platform.houzz.com/js/widgets.js?"+(new Date().getTime());var ss=d.getElementsByTagName('script')[0];ss.parentNode.insertBefore(js,ss);}})(document,"script","houzzwidget-js");
I've created a fiddle, but that's displaying different behaviour - I have to remove the width / height from the svg to make the widget work:
https://jsfiddle.net/v0fkr8jx/
My test page:
http://uprightconstruction.co.uk/index2
Here's the Houzz script being referenced. The error is around line 16 going by Firebug:
window.hzmr = window.hzmr || []; window.hzmr.push("widgets:2406");
(function() {
function createIFrame(width, height) {
var iframeElem = document.createElement('iframe');
iframeElem.setAttribute("scrolling","no");
iframeElem.allowTransparency = true;
iframeElem.border = 0;
iframeElem.frameBorder = 0;
iframeElem.style.border = 'none';
iframeElem.width = width;
iframeElem.height = height;
return iframeElem;
}
function containsClassName(elem, className) {
var classNames = elem.className.split(' ');
for(var i=0; i<classNames.length; i++) {
if(className == classNames[i]) {
return true;
}
}
return false;
}
function cleanLocale(locale) {
var knownLocales = {"en-us":true,"en-gb":true,"en-au":true,"de-de":true,"fr-fr":true,"ru-ru":true,"ja-jp":true,"it-it":true,"es-es":true,"da-dk":true,"nb-no":true,"fi-fi":true,"sv-se":true,"en-ie":true,"en-nz":true,"en-sg":true,"en-in":true};
if(locale && locale.toLowerCase() in knownLocales) {
return locale.toLowerCase();
}
return 'en-us';
}
function processWidgets(domId) {
var links = [];
if(typeof domId == 'string') {
if(domId.charAt(0) == '#') {
domId = domId.substr(1);
}
var elem = document.getElementById(domId);
if(elem) {
links.push(elem);
}
} else if(typeof domId != 'undefined' && ('nodeName' in domId)) {
links.push(domId);
} else {
links = document.getElementsByTagName('a');
}
var pid = new Date().getTime() + '' + Math.floor(Math.random()*1000000);
var houzzLinks = [];
var houzzReviews = [];
for (var i=0; i < links.length; i++) {
if(containsClassName(links[i],'houzz-share-button')) {
houzzLinks.push(links[i]);
} else if(containsClassName(links[i], 'houzz-review-widget')) {
houzzReviews.push(links[i]);
}
}
for (var i=0; i < houzzReviews.length; i++) {
var review = houzzReviews[i];
var pro = review.getAttribute('data-pro');
var mini = review.getAttribute('data-size');
mini = (mini == 'mini');
var locale = cleanLocale(review.getAttribute('data-locale'));
var iframeWidth = mini?225:300;
var iframeHeight = mini?130:435;
if(pro) {
var reviewUrls = {"en-us":"http:\/\/www.houzz.com\/reviewWidget","en-gb":"http:\/\/www.houzz.co.uk\/reviewWidget","en-au":"http:\/\/www.houzz.com.au\/reviewWidget","de-de":"http:\/\/www.houzz.de\/reviewWidget","fr-fr":"http:\/\/www.houzz.fr\/reviewWidget","ru-ru":"http:\/\/www.houzz.ru\/reviewWidget","ja-jp":"http:\/\/www.houzz.jp\/reviewWidget","it-it":"http:\/\/www.houzz.it\/reviewWidget","es-es":"http:\/\/www.houzz.es\/reviewWidget","da-dk":"http:\/\/www.houzz.dk\/reviewWidget","nb-no":"http:\/\/www.houzz.no\/reviewWidget","fi-fi":"http:\/\/www.houzz.fi\/reviewWidget","sv-se":"http:\/\/www.houzz.se\/reviewWidget","en-ie":"http:\/\/www.houzz.ie\/reviewWidget","en-nz":"http:\/\/www.houzz.co.nz\/reviewWidget","en-sg":"http:\/\/www.houzz.com.sg\/reviewWidget","en-in":"http:\/\/www.houzz.in\/reviewWidget"};
var iframeSrc = reviewUrls[locale] + '/' + encodeURIComponent(pro) + '/' + (mini?'mini':'');
var iframeElem = createIFrame(iframeWidth, iframeHeight);
review.parentNode.replaceChild(iframeElem, review);
iframeElem.src = iframeSrc;
}
}
for (var i=0; i < houzzLinks.length; i++) {
var link = houzzLinks[i];
var imageURL = link.getAttribute('data-img');
var linkURL = link.getAttribute('data-url');
var title = link.getAttribute('data-title');
var showCount = link.getAttribute('data-showcount') == '1';
var hzID = link.getAttribute('data-hzid');
var whiteBg = link.getAttribute('data-whitebg');
var format = link.getAttribute('data-format');
var locale = cleanLocale(link.getAttribute('data-locale'));
var identifier = i + '' + Math.floor(Math.random()*1000000);
link.id = 'hzbtn' + identifier;
var referer = document.location.href;
var buttonWidths = {"en-us":52,"en-gb":52,"en-au":52,"de-de":75,"fr-fr":88,"ru-ru":52,"ja-jp":52,"it-it":52,"es-es":52,"da-dk":52,"nb-no":52,"fi-fi":52,"sv-se":52,"en-ie":52,"en-nz":52,"en-sg":52,"en-in":52};
var buttonWidth = buttonWidths[locale];
var buttonUrls = {"en-us":"http:\/\/www.houzz.com\/buttonWidget","en-gb":"http:\/\/www.houzz.co.uk\/buttonWidget","en-au":"http:\/\/www.houzz.com.au\/buttonWidget","de-de":"http:\/\/www.houzz.de\/buttonWidget","fr-fr":"http:\/\/www.houzz.fr\/buttonWidget","ru-ru":"http:\/\/www.houzz.ru\/buttonWidget","ja-jp":"http:\/\/www.houzz.jp\/buttonWidget","it-it":"http:\/\/www.houzz.it\/buttonWidget","es-es":"http:\/\/www.houzz.es\/buttonWidget","da-dk":"http:\/\/www.houzz.dk\/buttonWidget","nb-no":"http:\/\/www.houzz.no\/buttonWidget","fi-fi":"http:\/\/www.houzz.fi\/buttonWidget","sv-se":"http:\/\/www.houzz.se\/buttonWidget","en-ie":"http:\/\/www.houzz.ie\/buttonWidget","en-nz":"http:\/\/www.houzz.co.nz\/buttonWidget","en-sg":"http:\/\/www.houzz.com.sg\/buttonWidget","en-in":"http:\/\/www.houzz.in\/buttonWidget"};
var iframeSrc = buttonUrls[locale] + '?url='
+ encodeURIComponent(linkURL);
if(imageURL) {
iframeSrc += '&img=' + encodeURIComponent(imageURL);
}
if(title) {
iframeSrc += '&title=' + encodeURIComponent(title);
}
if(showCount) {
iframeSrc += '&count=1';
}
if(whiteBg) {
var whiteBgValue = 0;
if(String(whiteBg) == '1' || whiteBg.toLowerCase() == 'true') {
whiteBgValue = 2;
} else if(String(whiteBg) == '0' || whiteBg.toLowerCase() == 'false') {
whiteBgValue = 1;
}
iframeSrc += '&whiteBg=' + encodeURIComponent(whiteBgValue);
}
if(hzID) {
iframeSrc += '&hzid=' + encodeURIComponent(hzID);
}
iframeSrc += '&locale=' + encodeURIComponent(locale);
iframeSrc += '&ref=' + encodeURIComponent(referer);
iframeSrc += '&pid=' + encodeURIComponent(pid);
if(format == 'custom') {
if(link.getAttribute('data-loaded') == '1') { continue; }
iframeSrc += '&fmt=' + encodeURIComponent(format);
iframeSrc += '&domid=' + encodeURIComponent(identifier);
var extElem = document.createElement('script');
extElem.setAttribute('type','text/javascript');
extElem.id = 'hzjs' + encodeURIComponent(identifier);
extElem.src = iframeSrc;
link.parentNode.appendChild(extElem);
} else {
var iframeElem = createIFrame(buttonWidth + (showCount?57:0), 20);
link.parentNode.replaceChild(iframeElem, link);
iframeElem.src = iframeSrc;
}
}
}
window.houzz = window.houzz || {};
window.houzz.processWidgets = processWidgets;
processWidgets();
})();
Any ideas about what's causing this?
This is because the script you are loading is getting all elements named a.
This will take HTML and SVG <a> elements without distinction.
The problem is that for SVG elements, the class attribute or className property is animatable. Which means that when you call a.className, you'll get an SVGAnimatedString Object, composed of two strings in two keys : baseVal and animVal.
Each of these keys has a split method, but not the SVGAnimatedString itself.
So the code should be modified to either find out if this is an HTML <a> (by checking its namespaceURI property), or to check if the split method is available before calling it, or by calling elem.getAttribute('class') instead of elem.className.

Categories