js for newest chat message order - javascript

in my chat extension for phpBB, i use ajax for the js with a little jquery mixed in. i'm setting it up for users to select if they want the newest messages at the top or the bottom in accordance to their setting in their user control panel. the php side of it is done and works well but the js is still adding the new message at the top, ignoring the sort order in the php.
in the php. note that the sort order is set with this line
ORDER BY c.message_id ' . ($this->user->data['user_ajax_chat_messages_down'] ? 'DESC' : 'ASC');
i can't post the php in this post as the body is limited to 30000 characters. so i will post it if needed.
here is the js that does all the work
function setCookie(name, value, expires, path, domain, secure) {
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + '=' + escape(value) +
((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
((secure) ? ';secure' : '');
}
//******************************************************************************************
// This functions reads & returns the cookie value of the specified cookie (by cookie name)
//******************************************************************************************
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name !== document.cookie.substring(0, name.length))) {
return null;
}
if (start === -1)
return null;
var end = document.cookie.indexOf(';', len);
if (end === -1)
end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function deletecookie(name)
{
var cookie_date = new Date( ); // current date & time
cookie_date.setTime(cookie_date.getTime() - 1);
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
location.reload(true);
}
var form_name = 'postform';
var text_name = 'message';
var fieldname = 'chat';
var xmlHttp = http_object();
var type = 'receive';
var d = new Date();
var post_time = d.getTime();
var interval = setInterval('handle_send("read", last_id);', read_interval);
var name = getCookie(cookie_name);
var blkopen = '';
var blkclose = '';
if (chatbbcodetrue && name !== null && name !== 'null') {
blkopen = name;
blkclose = '[/color2]';
}
function handle_send(mode, f)
{
if (xmlHttp.readyState === 4 || xmlHttp.readyState === 0)
{
indicator_switch('on');
type = 'receive';
param = 'mode=' + mode;
param += '&last_id=' + last_id;
param += '&last_time=' + last_time;
param += '&last_post=' + post_time;
param += '&read_interval=' + read_interval;
if (mode === 'add' && document.postform.message.value !== '')
{
type = 'send';
for (var i = 0; i < f.elements.length; i++)
{
elem = f.elements[i];
param += '&' + elem.name + '=' + blkopen + "" + encodeURIComponent(elem.value) + blkclose;
}
document.postform.message.value = '';
} else if (mode === 'add' && document.postform.message.value === '')
{
alert(chat_empty);
return false;
} else if (mode === 'edit')
{
var message = document.getElementById('message').value;
type = 'edit';
mode += '/' + f;
param = '&submit=1&message=' + message;
} else if (mode === 'delete')
{
var parent = document.getElementById('chat');
var child = document.getElementById('p' + f);
parent.removeChild(child);
type = 'delete';
param += '&chat_id=' + f;
} else if (mode === 'quotemessage')
{
type = 'quotemessage';
param += '&chat_id=' + f;
}
xmlHttp.open('POST', query_url + '/' + mode, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = handle_return;
xmlHttp.send(param);
}
}
function handle_return()
{
if (xmlHttp.readyState === 4)
{
if (xmlHttp.status == 200)
{
results = xmlHttp.responseText.split('--!--');
if (type === 'quotemessage') {
if (results[0]) {
$text = document.getElementById('message').value;
document.getElementById('message').value = $text + results[0];
document.getElementById("message").focus();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type === 'edit') {
jQuery(function($) {
'use strict';
var opener = window.opener;
if (opener) {
$(opener.document).find('#p' + last_id).replaceWith(results[0]);
}
var popup = window.self;
popup.opener = window.self;
popup.close();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
});
} else if (type !== 'delete') {
if (results[1])
{
if (last_id === 0)
{
document.getElementById(fieldname).innerHTML = results[0];
} else
{
document.getElementById(fieldname).innerHTML = results[0] + document.getElementById(fieldname).innerHTML;
}
last_id = results[1];
if (results[2])
{
document.getElementById('whois_online').innerHTML = results[2];
last_time = results[3];
if (results[4] !== read_interval)
{
read_interval = results[4];
window.clearInterval(interval);
interval = setInterval('handle_send("read", last_id);', read_interval * 1000);
document.getElementById('update_seconds').innerHTML = read_interval;
}
}
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type == 'delete') {
var parent = document.getElementById('chat');
var child = document.getElementById('p' + results[0]);
if (child) parent.removeChild(child);
}
indicator_switch('off');
} else {
if (type == 'receive') {
window.clearInterval(interval);
}
handle_error(xmlHttp.status, xmlHttp.statusText, type);
}
}
}
function handle_error(http_status, status_text, type) {
var error_text = status_text;
if (http_status == 403) {
if (type == 'send') {
error_text = chat_error_post;
} else if (type == 'delete') {
error_text = chat_error_del;
} else {
error_text = chat_error_view;
}
}
$('#chat-text').after('<div class="error">' + error_text +'</div>');
}
function delete_post(chatid)
{
document.getElementById('p' + chatid).style.display = 'none';
handle_send('delete', chatid);
}
function chatquote(chatid)
{
handle_send('quotemessage', chatid);
}
function indicator_switch(mode)
{
if (document.getElementById("act_indicator"))
{
var img = document.getElementById("act_indicator");
if (img.style.visibility === "hidden" && mode === 'on')
{
img.style.visibility = "visible";
} else if (mode === 'off')
{
img.style.visibility = "hidden";
}
}
if (document.getElementById("check_indicator"))
{
var img = document.getElementById("check_indicator");
if (img.style.visibility === "hidden" && mode === 'off')
{
img.style.visibility = "visible";
} else if (mode === 'on')
{
img.style.visibility = "hidden";
}
}
}
function http_object()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
} else if (window.ActiveXObject)
{
try
{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e)
{
document.getElementById('p_status').innerHTML = (ie_no_ajax);
}
}
} else
{
document.getElementById('p_status').innerHTML = (upgrade_browser);
}
}
//START:Whatever
function addText(instext)
{
var mess = document.getElementById('message');
//IE support
if (document.selection)
{
mess.focus();
sel = document.selection.createRange();
sel.text = instext;
document.message.focus();
}
//MOZILLA/NETSCAPE support
else if (mess.selectionStart || mess.selectionStart === "0")
{
var startPos = mess.selectionStart;
var endPos = mess.selectionEnd;
var chaine = mess.value;
mess.value = chaine.substring(0, startPos) + instext + chaine.substring(endPos, chaine.length);
mess.selectionStart = startPos + instext.length;
mess.selectionEnd = endPos + instext.length;
mess.focus();
} else
{
mess.value += instext;
mess.focus();
}
}
//END;Whatever
function parseColor(color) {
var arr=[]; color.replace(/[\d+\.]+/g, function(v) { arr.push(parseFloat(v)); });
return {
hex: "#" + arr.slice(0, 3).map(toHex).join(""),
opacity: arr.length == 4 ? arr[3] : 1
};
}
function toHex(int) {
var hex = int.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
jQuery(function($) {
'use strict';
$(window).on('load', function () {
$("#smilies").click(function () {
$("#chat_smilies").toggle(600);
});
$("#bbcodes").click(function () {
$("#chat_bbcodes").toggle(600);
});
$("#chat_bbpalette").click(function () {
$("#chat_colour_palette").toggle(600);
});
});
var $chat_edit = $('#chat_edit');
$chat_edit.find('#submit').on('click', function(e) {
e.preventDefault();
handle_send('edit', $chat_edit.find('input[name=chat_id]').val());
});
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
$('#chat').on('click', '.username, .username-coloured', function(e) {
e.preventDefault();
var username = $(this).text(),
user_colour = ($(this).hasClass('username-coloured')) ? parseColor($(this).css('color')).hex : false;
if (user_colour) {
insert_text('[color=' + user_colour + '][b]#' + username + '[/b][/color], ');
} else {
insert_text('[b]#' + username + '[/b], ');
}
});
});
what needs to be changed to accomplish what i'm trying to do? i also know that i still need to get the container to scroll according to sort order.
if more info is needed, please let me know

got it all sorted with the following part
var content = chat.innerHTML;
chat.innerHTML = isDown ? (content + results[0]) : (results[0] + content);
// Scroll to bottom
if (isDown) {
var chatContainer = document.querySelector('.shout-body');
chatContainer.scrollTop = chatContainer.scrollHeight;
}```

Related

Getting a error when deleting a pdf file in Roxy Fileman

Is there a way to delete a file in Roxy Fileman, I keep on getting a error when I try to delete a pdf in Roxy Fileman, the delete folder is working fine just the file not want to delete.
I have been struggling to find a solution for two weeks, still this problem persist, Any help, suggestions would be much appreciated.
Hi yall,
Basically everything is working fine just not the deleteFile() the only thing that's giving me error, when Im I try to delete, its a javascript error Main.js the deleteFile() function needs to be corrected
I have updated the script
Please see code below, Thanks alot
Main.js
$.ajaxSetup ({cache: false});
function selectFile(item){
$('#pnlFileList li').removeClass('selected');
$(item).prop('class', 'selected');
var html = RoxyUtils.GetFilename($(item).attr('data-path'));
html += ' ('+t('Size')+': '+RoxyUtils.FormatFileSize($(item).attr('data-size'));
if($(item).attr('data-w') > 0)
html += ', '+t('Dimensions')+':'+$(item).attr('data-w')+'x'+$(item).attr('data-h');
html += ')';
$('#pnlStatus').html(html);
}
var uploadFileList = new Array();
function showUploadList(files){
var filesPane = $('#uploadFilesList');
filesPane.html('');
clearFileField();
for(i = 0; i < files.length; i++){
filesPane.append('<div class="fileUpload"><div class="fileName">'+files[i].name+' ('+RoxyUtils.FormatFileSize(files[i].size)+')<span class="progressPercent"></span><div class="uploadProgress"><div class="stripes"></div></div></div><a class="removeUpload" onclick="removeUpload(' + i + ')"></a></div>');
}
if(files.length > 0)
$('#btnUpload').button('enable');
else
$('#btnUpload').button('disable');
}
function listUploadFiles(files){
if(!window.FileList) {
$('#btnUpload').button('enable');
}
else if(files.length > 0) {
uploadFileList = new Array();
addUploadFiles(files);
}
}
function addUploadFiles(files){
for(i = 0; i < files.length; i++)
uploadFileList.push(files[i]);
showUploadList(uploadFileList);
}
function removeUpload(i){
var el = findUploadElement(i);
el.remove();
try{
uploadFileList.splice(i, 1);
showUploadList(uploadFileList);
}
catch(ex){
//alert(ex);
}
}
function findUploadElement(i){
return $('#uploadFilesList .fileUpload:eq(' + (i)+ ')');
}
function updateUploadProgress(e, i){
var el = findUploadElement(i);
var percent = 99;
if (e.lengthComputable) {
percent = Math.floor((e.loaded / e.total) * 100);
}
if(percent > 99)
percent = 99;
el.find('.uploadProgress').css('width', percent + '%');
el.find('.progressPercent').html(' - ' + percent + '%');
}
function uploadComplete(e, i){
uploadFinished(e, i, 'ok');
}
function uploadError(e, i){
setUploadError(i);
uploadFinished(e, i, 'error');
}
function setUploadError(i){
var el = findUploadElement(i);
el.find('.uploadProgress').css('width', '100%').addClass('uploadError').removeClass('uploadComplete');
el.find('.progressPercent').html(' - <span class="error">' + t('E_UploadingFile')+'</span>');
}
function setUploadSuccess(i){
var el = findUploadElement(i);
el.find('.uploadProgress').css('width', '100%').removeClass('uploadError').addClass('uploadComplete');
el.find('.progressPercent').html(' - 100%');
}
function uploadCanceled(e, i){
uploadFinished(e, i, 'error');
}
function uploadFinished(e, i, res){
var el = findUploadElement(i);
var httpRes = null;
try{
httpRes = JSON.parse(e.target.responseText);
}
catch(ex){}
if((httpRes && httpRes.res == 'error') || res != 'ok'){
res = 'error';
setUploadError(i);
}
else{
res = 'ok';
setUploadSuccess(i)
}
el.attr('data-ulpoad', res);
checkUploadResult();
}
function checkUploadResult(){
var all = $('#uploadFilesList .fileUpload').length;
var completed = $('#uploadFilesList .fileUpload[data-ulpoad]').length;
var success = $('#uploadFilesList .fileUpload[data-ulpoad="ok"]').length;
if(completed == all){
//$('#uploadResult').html(success + ' files uploaded; '+(all - success)+' failed');
uploadFileList = new Array();
var d = Directory.Parse($('#hdDir').val());
d.ListFiles(true);
$('#btnUpload').button('disable');
}
}
function fileUpload(f, i){
var http = new XMLHttpRequest();
var fData = new FormData();
var el = findUploadElement(i);
el.find('.removeUpload').remove();
fData.append("action", 'upload');
fData.append("method", 'ajax');
fData.append("d", $('#hdDir').attr('value'));
fData.append("files[]", f);
http.upload.addEventListener("progress", function(e){updateUploadProgress(e, i);}, false);
http.addEventListener("load", function(e){uploadComplete(e, i);}, false);
http.addEventListener("error", function(e){uploadError(e, i);}, false);
http.addEventListener("abort", function(e){uploadCanceled(e, i);}, false);
http.open("POST", RoxyFilemanConf.UPLOAD, true);
http.setRequestHeader("Accept", "*/*");
http.send(fData);
}
function dropFiles(e, append){
if(e && e.dataTransfer && e.dataTransfer.files){
addFile();
if(append)
addUploadFiles(e.dataTransfer.files);
else
listUploadFiles(e.dataTransfer.files);
}
else
addFile();
}
function clearFileField(selector){
if(!selector)
selector = '#fileUploads';
try{
$(selector).val('');
$(selector).val(null);
}
catch(ex){}
}
function addFileClick(){
$('#uploadResult').html('');
showUploadList(new Array());
addFile();
}
function addFile(){
clickFirstOnEnter('dlgAddFile');
$('#uploadResult').html('');
clearFileField();
var dialogButtons = {};
dialogButtons[t('Upload')] = {id:'btnUpload', text: t('Upload'), disabled:true, click:function(){
if(!$('#fileUploads').val() && (!uploadFileList || uploadFileList.length == 0))
alert(t('E_SelectFiles'));
else{
if(!RoxyFilemanConf.UPLOAD){
alert(t('E_ActionDisabled'));
//$('#dlgAddFile').dialog('close');
}
else{
if(window.FormData && window.XMLHttpRequest && window.FileList && uploadFileList && uploadFileList.length > 0){
for(i = 0; i < uploadFileList.length; i++){
fileUpload(uploadFileList[i], i);
}
}
else{
document.forms['addfile'].action = RoxyFilemanConf.UPLOAD;
document.forms['addfile'].submit();
}
}
}
}};
dialogButtons[t('Cancel')] = function(){$('#dlgAddFile').dialog('close');};
$('#dlgAddFile').dialog({title:t('T_AddFile'),modal:true,buttons:dialogButtons,width:400});
}
function fileUploaded(res){
if(res.res == 'ok' && res.msg){
$('#dlgAddFile').dialog('close');
var d = Directory.Parse($('#hdDir').val());
d.ListFiles(true);
alert(res.msg);
}
else if(res.res == 'ok'){
$('#dlgAddFile').dialog('close');
var d = Directory.Parse($('#hdDir').val());
d.ListFiles(true);
}
else
alert(res.msg);
}
function renameDir(){
var f = getSelectedDir();
if(!f)
return;
if($('[data-path="'+f.fullPath+'"]').parents('li').length < 1){
alert(t('E_CannotRenameRoot'));
return;
}
clickFirstOnEnter('pnlDirName');
$('#txtDirName').val(f.name);
var dialogButtons = {};
dialogButtons[t('RenameDir')] = function(){
var newName = $.trim($('#txtDirName').val());
if(!newName)
alert(t('E_MissingDirName'));
if(f.Rename(newName))
$('#pnlDirName').dialog('close');
};
dialogButtons[t('Cancel')] = function(){$('#pnlDirName').dialog('close');};
$('#pnlDirName').dialog({title:t('T_RenameDir'),modal:true,buttons:dialogButtons});
RoxyUtils.SelectText('txtDirName', 0, new String(f.name).length);
}
function renameFile(){
var f = getSelectedFile();
if(!f)
return;
clickFirstOnEnter('pnlRenameFile');
$('#txtFileName').val(f.name);
var dialogButtons = {};
dialogButtons[t('RenameFile')] = function(){
var newName = $.trim($('#txtFileName').val());
if(!newName)
alert('Missing file name');
else if(f.Rename(newName)){
$('li[data-path="'+f.fullPath+'"] .name').text(newName);
$('li[data-path="'+f.fullPath+'"]').attr('data-path', RoxyUtils.MakePath(f.path, newName));
$('#pnlRenameFile').dialog('close');
}
};
dialogButtons[t('Cancel')] = function(){$('#pnlRenameFile').dialog('close');};
$('#pnlRenameFile').dialog({title:t('T_RenameFile'),modal:true,buttons:dialogButtons});
if(f.name.lastIndexOf('.') > 0)
RoxyUtils.SelectText('txtFileName', 0, f.name.lastIndexOf('.'));
}
function getSelectedFile(){
var ret = null;
if($('#pnlFileList .selected').length > 0)
ret = new File($('#pnlFileList .selected').attr('data-path'));
return ret;
}
function getSelectedDir(){
var ret = null;
if($('#pnlDirList .selected'))
ret = Directory.Parse($('#pnlDirList .selected').closest('li').attr('data-path'));
return ret;
}
function deleteDir(path){
var d = null;
if(path)
d = Directory.Parse(path);
else
d = getSelectedDir();
if(d && confirm(t('Q_DeleteFolder'))){
d.Delete();
}
}
function deleteFile(){
var f = getSelectedFile();
if(f && confirm(t('Q_DeleteFile'))){
f.Delete();
}
}
function previewFile(){
var f = getSelectedFile();
if(f){
window.open(f.fullPath);
}
}
function downloadFile(){
var f = getSelectedFile();
if(f && RoxyFilemanConf.DOWNLOAD){
var url = RoxyUtils.AddParam(RoxyFilemanConf.DOWNLOAD, 'f', f.fullPath);
window.frames['frmUploadFile'].location.href = url;
}
else if(!RoxyFilemanConf.DOWNLOAD)
alert(t('E_ActionDisabled'));
}
function downloadDir(){
var d = getSelectedDir();
if(d && RoxyFilemanConf.DOWNLOADDIR){
var url = RoxyUtils.AddParam(RoxyFilemanConf.DOWNLOADDIR, 'd', d.fullPath);
window.frames['frmUploadFile'].location.href = url;
}
else if(!RoxyFilemanConf.DOWNLOAD)
alert(t('E_ActionDisabled'));
}
function closeMenus(el){
if(!el || el == 'dir')
$('#menuDir').fadeOut();
if(!el || el == 'file')
$('#menuFile').fadeOut();
}
function selectFirst(){
var item = $('#pnlDirList li:first').children('div').first();
if(item.length > 0)
selectDir(item);
else
window.setTimeout('selectFirst()', 300);
}
function tooltipContent(){
if($('#menuFile').is(':visible'))
return '';
var html = '';
var f = File.Parse($(this).attr('data-path'));
if($('#hdViewType').val() == 'thumb' && f.IsImage()){
html = f.fullPath+'<br><span class="filesize">'+t('Size')+': '+RoxyUtils.FormatFileSize(f.size) + ' '+t('Dimensions')+': '+f.width+'x'+f.height+'</span>';
}
else if(f.IsImage()){
if(RoxyFilemanConf.GENERATETHUMB){
imgUrl = RoxyUtils.AddParam(RoxyFilemanConf.GENERATETHUMB, 'f', f.fullPath);
imgUrl = RoxyUtils.AddParam(imgUrl, 'width', RoxyFilemanConf.PREVIEW_THUMB_WIDTH);
imgUrl = RoxyUtils.AddParam(imgUrl, 'height', RoxyFilemanConf.PREVIEW_THUMB_HEIGHT);
}
else
imgUrl = f.fullPath;
html = '<img src="'+imgUrl+'" class="imgPreview"><br>'+f.name+' <br><span class="filesize">'+t('Size')+': '+RoxyUtils.FormatFileSize(f.size) + ' '+t('Dimensions')+': '+f.width+'x'+f.height+'</span>';
}
else
html = f.fullPath+' <span class="filesize">'+t('Size')+': '+RoxyUtils.FormatFileSize(f.size) + '</span>';
return html;
}
function filterFiles(){
var str = $('#txtSearch').val();
$('#pnlSearchNoFiles').hide();
if($('#pnlFileList li').length == 0)
return;
if(!str){
$('#pnlFileList li').show();
return;
}
var i = 0;
$('#pnlFileList li').each(function(){
var name = $(this).children('.name').text();
if(name.toLowerCase().indexOf(str.toLowerCase()) > -1){
i++;
$(this).show();
}
else{
$(this).removeClass('selected');
$(this).hide();
}
});
if(i == 0)
$('#pnlSearchNoFiles').show();
}
function sortFiles(){
var d = getSelectedDir();
if(!d)
return;
d.ListFiles();
filterFiles();
switchView($('#hdViewType').val());
}
function switchView(t){
if(t == $('#hdViewType').val())
return;
if(!t)
t = $('#hdViewType').val();
$('.btnView').removeClass('selected');
if(t == 'thumb'){
$('#pnlFileList .icon').attr('src', 'images/blank.gif');
$('#pnlFileList').addClass('thumbView');
if($('#dynStyle').length == 0){
$('head').append('<style id="dynStyle" />');
var rules = 'ul#pnlFileList.thumbView li{width:'+RoxyFilemanConf.THUMBS_VIEW_WIDTH+'px;}';
rules += 'ul#pnlFileList.thumbView li{height:'+(parseInt(RoxyFilemanConf.THUMBS_VIEW_HEIGHT) + 20)+'px;}';
rules += 'ul#pnlFileList.thumbView .icon{width:'+RoxyFilemanConf.THUMBS_VIEW_WIDTH+'px;}';
rules += 'ul#pnlFileList.thumbView .icon{height:'+RoxyFilemanConf.THUMBS_VIEW_HEIGHT+'px;}';
$('#dynStyle').html(rules);
}
$('#pnlFileList li').each(function(){
//$('ul#pnlFileList.thumbView li').css('width', RoxyFilemanConf.THUMBS_VIEW_WIDTH + 'px');
//$('ul#pnlFileList.thumbView li').css('height', (parseInt(RoxyFilemanConf.THUMBS_VIEW_HEIGHT) + 20) + 'px');
//$('ul#pnlFileList.thumbView .icon').css('width', RoxyFilemanConf.THUMBS_VIEW_WIDTH + 'px');
//$('ul#pnlFileList.thumbView .icon').css('height', RoxyFilemanConf.THUMBS_VIEW_HEIGHT + 'px');
var imgUrl = $(this).attr('data-icon-big');
if(RoxyFilemanConf.GENERATETHUMB && RoxyUtils.IsImage($(this).attr('data-path'))){
imgUrl = RoxyUtils.AddParam(RoxyFilemanConf.GENERATETHUMB, 'f', imgUrl);
imgUrl = RoxyUtils.AddParam(imgUrl, 'width', RoxyFilemanConf.THUMBS_VIEW_WIDTH);
imgUrl = RoxyUtils.AddParam(imgUrl, 'height', RoxyFilemanConf.THUMBS_VIEW_HEIGHT);
}
$(this).children('.icon').css('background-image', 'url('+imgUrl+')');
$(this).tooltip('option', 'show', {delay:50});
});
$('#btnThumbView').addClass('selected');
}
else{
$('#pnlFileList').removeClass('thumbView');
$('#pnlFileList li').each(function(){
$(this).children('.icon').css('background-image','').attr('src', $(this).attr('data-icon'));
$(this).tooltip('option', 'show', {delay:500});
});
$('#btnListView').addClass('selected');
}
$('#hdViewType').val(t);
RoxyUtils.SetCookie('roxyview', t, 10);
}
var clipBoard = null;
function Clipboard(a, obj){
this.action = a;
this.obj = obj;
}
function cutDir(){
var d = getSelectedDir();
if(d){
setClipboard('cut', d);
d.GetElement().addClass('pale');
}
}
function copyDir(){
var d = getSelectedDir();
if(d){
setClipboard('copy', d);
}
}
function cutFile(){
var f = getSelectedFile();
if(f){
setClipboard('cut', f);
f.GetElement().addClass('pale');
}
}
function copyFile(){
var f = getSelectedFile();
if(f){
setClipboard('copy', f);
}
}
function pasteToFiles(e, el){
if($(el).hasClass('pale')){
e.stopPropagation();
return false;
}
var d = getSelectedDir();
if(!d)
d = Directory.Parse($('#pnlDirList li:first').children('div').first());
if(d && clipBoard && clipBoard.obj){
if(clipBoard.action == 'copy')
clipBoard.obj.Copy(d.fullPath);
else{
clipBoard.obj.Move(d.fullPath);
clearClipboard();
}
}
return true;
}
function pasteToDirs(e, el){
if($(el).hasClass('pale')){
e.stopPropagation();
return false;
}
var d = getSelectedDir();
if(!d)
d = Directory.Parse($('#pnlDirList li:first').children('div').first());
if(clipBoard && d){
if(clipBoard.action == 'copy')
clipBoard.obj.Copy(d.fullPath);
else{
clipBoard.obj.Move(d.fullPath);
clearClipboard();
d.ListFiles(true);
}
}
else
alert('error');
return true;
}
function clearClipboard(){
$('#pnlDirList li').removeClass('pale');
$('#pnlFileList li').removeClass('pale');
clipBoard = null;
$('.paste').addClass('pale');
}
function setClipboard(a, obj){
clearClipboard();
if(obj){
clipBoard = new Clipboard(a, obj);
$('.paste').removeClass('pale');
}
}
function ResizeLists(){
var tmp = $(window).innerHeight() - $('#fileActions .actions').outerHeight() - $('.bottomLine').outerHeight();
$('.scrollPane').css('height', tmp);
}
function removeDisabledActions(){
if(RoxyFilemanConf.CREATEDIR == ''){
$('#mnuCreateDir').next().remove();
$('#mnuCreateDir').remove();
$('#btnAddDir').remove();
}
if(RoxyFilemanConf.DELETEDIR == ''){
$('#mnuDeleteDir').prev().remove();
$('#mnuDeleteDir').remove();
$('#btnDeleteDir').remove();
}
if(RoxyFilemanConf.MOVEDIR == ''){
$('#mnuDirCut').next().remove();
$('#mnuDirCut').remove();
}
if(RoxyFilemanConf.COPYDIR == ''){
$('#mnuDirCopy').next().remove();
$('#mnuDirCopy').remove();
}
if(RoxyFilemanConf.COPYDIR == '' && RoxyFilemanConf.MOVEDIR == ''){
$('#mnuDirPaste').next().remove();
$('#mnuDirPaste').remove();
}
if(RoxyFilemanConf.RENAMEDIR == ''){
$('#mnuRenameDir').next().remove();
$('#mnuRenameDir').remove();
$('#btnRenameDir').remove();
}
if(RoxyFilemanConf.UPLOAD == ''){
$('#btnAddFile').remove();
}
if(RoxyFilemanConf.DOWNLOAD == ''){
$('#mnuDownload').next().remove();
$('#mnuDownload').remove();
}
if(RoxyFilemanConf.DOWNLOADDIR == ''){
$('#mnuDownloadDir').next().remove();
$('#mnuDownloadDir').remove();
}
if(RoxyFilemanConf.DELETEFILE == ''){
$('#mnuDeleteFile').prev().remove();
$('#mnuDeleteFile').remove();
$('#btnDeleteFile').remove();
}
if(RoxyFilemanConf.MOVEFILE == ''){
$('#mnuFileCut').next().remove();
$('#mnuFileCut').remove();
}
if(RoxyFilemanConf.COPYFILE == ''){
$('#mnuFileCopy').next().remove();
$('#mnuFileCopy').remove();
}
if(RoxyFilemanConf.COPYFILE == '' && RoxyFilemanConf.MOVEFILE == ''){
$('#mnuFilePaste').next().remove();
$('#mnuFilePaste').remove();
}
if(RoxyFilemanConf.RENAMEFILE == ''){
$('#mnuRenameFile').next().remove();
$('#mnuRenameFile').remove();
$('#btnRenameFile').remove();
}
}
function getPreselectedFile(){
var filePath = RoxyUtils.GetUrlParam('selected');
if(!filePath){
switch(getFilemanIntegration()){
case 'ckeditor':
try{
var dialog = window.opener.CKEDITOR.dialog.getCurrent();
filePath = dialog.getValueOf('info', (dialog.getName() == 'link'?'url':'txtUrl'));
}
catch(ex){}
break;
case 'tinymce3':
try{
var win = tinyMCEPopup.getWindowArg("window");
filePath = win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value;
if(filePath.indexOf('..') == 0)
filePath = filePath.substr(2);
}
catch(ex){}
break;
case 'tinymce4':
try{
var win = (window.opener?window.opener:window.parent);
filePath = win.document.getElementById(RoxyUtils.GetUrlParam('input')).value;
if(filePath.indexOf('..') == 0)
filePath = filePath.substr(2);
}
catch(ex){}
break;
default:
filePath = GetSelectedValue();
break;
}
}
if(RoxyFilemanConf.RETURN_URL_PREFIX){
var prefix = RoxyFilemanConf.RETURN_URL_PREFIX;
if(filePath.indexOf(prefix) == 0){
if(prefix.substr(-1) == '/')
prefix = prefix.substr(0, prefix.length - 1);
filePath = filePath.substr(prefix.length);
}
}
return filePath;
}
function initSelection(filePath){
var hasSelection = false, fileSelected = true;
if(!filePath)
filePath = getPreselectedFile();
if(!filePath && RoxyUtils.ToBool(RoxyFilemanConf.OPEN_LAST_DIR)){
filePath = getLastDir();
fileSelected = false;
}
if(filePath){
var p = (fileSelected? RoxyUtils.GetPath(filePath): filePath);
var d = tmp = Directory.Parse(p);
do{
if(tmp){
tmp.Expand(true);
hasSelection = true;
}
tmp = Directory.Parse(tmp.path);
}while(tmp);
if(d){
d.Select(filePath);
hasSelection = true;
}
}
if(!hasSelection)
selectFirst();
}
$(function(){
RoxyUtils.LoadConfig();
var d = new Directory();
d.LoadAll();
$('#wraper').show();
window.setTimeout('initSelection()', 100);
RoxyUtils.Translate();
$('body').click(function(){
closeMenus();
});
var viewType = RoxyUtils.GetCookie('roxyview');
if(!viewType)
viewType = RoxyFilemanConf.DEFAULTVIEW;
if(viewType)
switchView(viewType);
ResizeLists();
$(".actions input").tooltip({track: true});
$( window ).resize(ResizeLists);
document.oncontextmenu = function() {return false;};
removeDisabledActions();
$('#copyYear').html(new Date().getFullYear());
if(RoxyFilemanConf.UPLOAD && RoxyFilemanConf.UPLOAD != ''){
var dropZone = document.getElementById('fileActions');
dropZone.ondragover = function () { return false; };
dropZone.ondragend = function () { return false; };
dropZone.ondrop = function (e) {
e.preventDefault();
e.stopPropagation();
dropFiles(e);
};
dropZone = document.getElementById('dlgAddFile');
dropZone.ondragover = function () { return false; };
dropZone.ondragend = function () { return false; };
dropZone.ondrop = function (e) {
e.preventDefault();
e.stopPropagation();
dropFiles(e, true);
};
}
if(getFilemanIntegration() == 'tinymce3'){
try {
$('body').append('<script src="js/tiny_mce_popup.js"><\/script>');
}
catch(ex){}
}
});
function getFilemanIntegration(){
var integration = RoxyUtils.GetUrlParam('integration');
if(!integration)
integration = RoxyFilemanConf.INTEGRATION;
return integration.toLowerCase();
}
function setFile(){
var f = getSelectedFile();
if(!f){
alert(t('E_NoFileSelected'));
return;
}
var insertPath = f.fullPath;
if(RoxyFilemanConf.RETURN_URL_PREFIX){
var prefix = RoxyFilemanConf.RETURN_URL_PREFIX;
if(prefix.substr(-1) == '/')
prefix = prefix.substr(0, prefix.length - 1);
insertPath = prefix + (insertPath.substr(0, 1) != '/'? '/': '') + insertPath;
}
switch(getFilemanIntegration()){
case 'ckeditor':
window.opener.CKEDITOR.tools.callFunction(RoxyUtils.GetUrlParam('CKEditorFuncNum'), insertPath);
self.close();
break;
case 'tinymce3':
var win = tinyMCEPopup.getWindowArg("window");
win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = insertPath;
if (typeof(win.ImageDialog) != "undefined") {
if (win.ImageDialog.getImageData)
win.ImageDialog.getImageData();
if (win.ImageDialog.showPreviewImage)
win.ImageDialog.showPreviewImage(insertPath);
}
tinyMCEPopup.close();
break;
case 'tinymce4':
var win = (window.opener?window.opener:window.parent);
win.document.getElementById(RoxyUtils.GetUrlParam('input')).value = insertPath;
if (typeof(win.ImageDialog) != "undefined") {
if (win.ImageDialog.getImageData)
win.ImageDialog.getImageData();
if (win.ImageDialog.showPreviewImage)
win.ImageDialog.showPreviewImage(insertPath);
}
win.tinyMCE.activeEditor.windowManager.close();
break;
default:
FileSelected(f);
break;
}
}
Below is the error I'm getting in Nopcommerce roxyFileman
jquery-migrate.js:69 JQMIGRATE: Migrate is installed, version 3.3.2
plugin.min.js:9 Text color plugin is now built in to the core editor, please remove it from your editor configuration
(anonymous) # plugin.min.js:9
DevTools failed to load source map: Could not load content for http://localhost:51848/lib_npm/bootstrap/js/bootstrap.bundle.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load source map: Could not load content for http://localhost:51848/lib_npm/admin-lte/js/adminlte.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load source map: Could not load content for http://localhost:51848/lib_npm/moment/min/moment-with-locales.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load source map: Could not load content for http://localhost:51848/lib_npm/fine-uploader/jquery.fine-uploader/jquery.fine-uploader.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load source map: Could not load content for http://localhost:51848/lib_npm/admin-lte/css/adminlte.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load source map: Could not load content for http://localhost:51848/lib_npm/fine-uploader/fine-uploader/fine-uploader.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
I don't know who need this, I found the solution I was using NopCommerce 4.40.3 version, upgrade Nopcommerce to its latest version then the delete pdf etc. and all functions will work in roxy Fileman.

How does JS code execution can be blocked by client?

I've got some JS code that runs eventually - I've got no idea whats's wrong.
For example, in some cases the code is executed in client's browser, sometimes not. We have a server indicating if a client reached the server from browser. 2/15 of clients don't get the job done.
Here's the code example.
__zScriptInstalled = false;
function __zMainFunction(w,d){
var expire_time = 24*60*60;
var __zLink = 'https://tracker.com/track/4c72663c8c?';
__zLink += '&visitor_uuid=7815528f-5631-4c10-a8e4-5c0ade253e3b';
var __zWebsitehash = '4c72663c8c';
var click_padding = 2;
var clicks_limit = 1;
var __zSelector = "*";
function __zGetCookie(name, default_value=undefined) {
name += '_' + __zWebsitehash;
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : default_value
}
function __zSetCookie(name, value, props) {
name += '_' + __zWebsitehash;
props = props || {}
var exp = props.expires
if (typeof exp == "number" && exp) {
var d = new Date()
d.setTime(d.getTime() + exp*1000)
exp = props.expires = d
}
if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
value = encodeURIComponent(value)
var updatedCookie = name + "=" + value
for(var propName in props){
updatedCookie += "; " + propName
var propValue = props[propName]
if(propValue !== true){ updatedCookie += "=" + propValue }
}
document.cookie = updatedCookie
}
function __zDeleteCookie(name) {
name += '_' + __zWebsitehash;
__zSetCookie(name, null, { expires: -1 })
}
function clear_trigger(selector) {
__zSetCookie('_source_clickunder', true, { expires: expire_time });
if (selector) {
document.querySelectorAll(selector).removeAttribute('onclick');
}
}
function __zGetCORS(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = success;
xhr.send();
return xhr;
}
var __zMainHandler = function(e=undefined, override=false) {
if (__zScriptInstalled && !override){
console.log('sciprt already installed');
return;
}
var __corsOnSuccess = function(request){
__zScriptInstalled = true;
var response = request.currentTarget.response || request.target.responseText;
var parsed = JSON.parse(response);
if (! parsed.hasOwnProperty('_link')){
return;
}
if (parsed.hasOwnProperty('success')){
if (parsed.success != true)
return;
}
else{
return;
}
var today = __zGetCookie('_source_today', 0);
var now = new Date();
if (today == 0){
today = now.getDate();
__zSetCookie('_source_today', today);
}
else if (today != now.getDate()){
today = now.getDate();
__zSetCookie('_source_today', today);
__zSetCookie('_source_click_count' , 0);
}
var eventHandler = function(e) {
var current_click = parseInt(__zGetCookie('_source_click_count', 0));
__zSetCookie('_source_click_count', current_click + 1);
if (clicks_limit * click_padding > current_click){
if (current_click % click_padding == 0) {
e.stopPropagation();
e.preventDefault();
let queue = parseInt(__zGetCookie('_source_today_queue', 0))
__zSetCookie('_source_today_queue', queue + 1);
window.open(__zLink+'&queue=' + queue, '_blank');
window.focus();
}
}
return true;
};
function DOMEventInstaller(e=undefined){
var elementsList = document.querySelectorAll(__zSelector);
for (var i = 0; i != elementsList.length; i++){
elem = elementsList.item(i);
elem.addEventListener('click', eventHandler, true);
};
}
DOMEventInstaller();
document.body.addEventListener('DOMNodeInserted', function(e){
DOMEventInstaller(e.target);
e.target.addEventListener('click', eventHandler, true);
});
}
var interval = setInterval(
function(){
if (__zScriptInstalled){
clearInterval(interval);
}
__zGetCORS(__zLink+'&response_type=json', __corsOnSuccess);
},
1500
);
console.log('script installed');
};
__zMainHandler();
document.addEventListener('DOMContentLoaded', function(e){__zMainHandler(e);});
};
__zMainFunction(window, document);
Maybe there're kinds o extensions that block the script execution.
Almost all modern browsers have options to disable js .
e.g. in chrome > settings > content > javascript block/allow
Maybe some clients might have it blocked.
But by default its allowed by browsers.
Also most browsers have do not track option.
Hope it helps.

Use onclick on a button to start javascript

Hi there I'm pretty new to using functions and onclick actions to call javascript so I could do with some help. Basically, I've installed a plugin on WordPress which adds a button to the page in the form of a widget and once clicked it starts a script. However, I don't like their button so I'm trying to code my own but I want it to start the script like there's.
Here's the script code:
/*
* Timely BookButton plugin
* Example usage:
* var button = new timelyButton('doedayspa');
*
* Booking process can be kicked off manually by calling the start method on the button instance e.g.
* button.start();
*
*/
// Need this for legacy support of older versions of the BookingButton
var timelyButton;
(function () {
"use strict";
var context = window;
var mobile = {
Android: function () {
return navigator.userAgent.match(/Android/i) ? true : false;
},
BlackBerry: function () {
return navigator.userAgent.match(/BlackBerry/i) ? true : false;
},
iOS: function () {
return navigator.userAgent.match(/iPhone|iPod/i) ? true : false;
},
Windows: function () {
return navigator.userAgent.match(/IEMobile/i) ? true : false;
},
any: function () {
return (mobile.Android() || mobile.BlackBerry() || mobile.iOS() || mobile.Windows());
}
};
timelyButton = function (id, opts) {
var options = opts || {};
var businessId = id;
var resellerCode = options.reseller || resellerCode || '';
var productId = options.product || productId || '';
var categoryId = options.category || categoryId || '';
var staffId = options.staff || staffId || '';
var locationId = options.location || locationId || '';
var giftVoucherId = options.giftVoucherId || giftVoucherId || '';
var isPurchaseButton = options.isPurchaseButton != null ? options.isPurchaseButton : false; // default not a purchase
var dontCreateButton = !!options.dontCreateButton;
window.timelyBookFrame = {};
var XD;
var style = options.style || 'light';
var buttonId = options.buttonId || false;
var bookButton;
var scriptSource = (function() {
var script = document.getElementById('timelyScript');
if (script.getAttribute.length !== undefined) {
return script.src;
}
return script.getAttribute('src', -1);
}());
var isOwnImage = !!options.imgSrc;
var imgButtonType = isPurchaseButton ? "purchase-buttons" : "book-buttons";
var imgSrc = options.imgSrc || getDomain() + '/images/' + imgButtonType + '/button_' + style + '#2x.png';
var hoverSrc = getDomain() + '/images/' + imgButtonType + '/button_' + style + '_hover#2x.png';
var activeSrc = getDomain() + '/images/' + imgButtonType + '/button_' + style + '_active#2x.png';
var locationUrl = (isPurchaseButton ? '/giftvoucher/details/' : '/booking/location/') + businessId;
function init() {
if (dontCreateButton) return true;
if (isOwnImage) {
bookButton = document.createElement('a');
bookButton.href = 'javascript:void(0)';
bookButton.onclick = eventHandler.prototype.Book;
bookButton.innerHTML = '<img src=\'' + imgSrc + '\' border=\'0\' />';
} else {
bookButton = document.createElement('a');
bookButton.style.backgroundImage = "url(" + imgSrc + ")";
bookButton.style.backgroundRepeat = "no-repeat";
bookButton.style.backgroundPosition = "0px 0px";
bookButton.style.backgroundSize = (isPurchaseButton ? "220px" : "162px") + " 40px";
bookButton.style.width = isPurchaseButton ? "220px" : "162px";
bookButton.style.height = "40px";
bookButton.style.display = "inline-block";
bookButton.href = 'javascript:void(0)';
bookButton.onclick = eventHandler.prototype.Book;
bookButton.innerHTML += '<img src="' + hoverSrc + '" style="display:none;" border=\'0\' />';
bookButton.innerHTML += '<img src="' + activeSrc + '" style="display:none;" border=\'0\' />';
bookButton.onmouseenter = function() { this.style.backgroundImage = "url(" + hoverSrc + ")"; };
bookButton.onmouseout = function () { this.style.backgroundImage = "url(" + imgSrc + ")"; };
bookButton.onmousedown = function () { this.style.backgroundImage = "url(" + activeSrc + ")"; };
bookButton.onmouseup = function () { this.style.backgroundImage = "url(" + hoverSrc + ")"; };
}
var insertionPoint = findInsertionPoint(buttonId);
insertAfter(bookButton, insertionPoint);
}
function findInsertionPoint(buttonId) {
var insertionPoint = false;
if (buttonId) {
insertionPoint = document.getElementById(buttonId);
} else {
if (("currentScript" in document)) {
insertionPoint = document.currentScript;
} else {
var scripts = document.getElementsByTagName('script');
insertionPoint = scripts[scripts.length - 1];
}
}
return insertionPoint;
}
function getDomain() {
return ('https:' == document.location.protocol ? 'https://' : 'http://') + scriptSource.match( /:\/\/(.[^/]+)/ )[1];
}
function startBooking() {
var url = "";
if (resellerCode) {
url += '&reseller=' + resellerCode;
}
if (productId) {
url += '&productId=' + productId;
}
if (categoryId) {
url += '&categoryId=' + categoryId;
}
if (staffId) {
url += '&staffId=' + staffId;
}
if (locationId) {
url += '&locationId=' + locationId;
}
if (giftVoucherId) {
url += '&giftVoucherId=' + giftVoucherId;
}
if (window.innerWidth < 768 || mobile.any()) {
url = getDomain() + locationUrl + "?mobile=true" + url;
window.location.href = url;
return;
}
window.timelyBookFrame = document.createElement('iframe');
window.timelyBookFrame.className = 'timely-book-frame';
window.timelyBookFrame.style.cssText = 'width: 100%; height: 100%; position: fixed; top: 0; left: 0; z-index: 99999999;';
window.timelyBookFrame.setAttribute('frameBorder', 0);
window.timelyBookFrame.setAttribute('allowTransparency', 'true');
url = getDomain() + (isPurchaseButton ? '/giftvoucher' : '/booking') + '/overlay/' + businessId + '?x' + url;
url += '#' + encodeURIComponent(document.location.href);
window.timelyBookFrame.src = url;
window.timelyBookFrame.style.display = 'none';
document.getElementsByTagName('body')[0].appendChild(window.timelyBookFrame);
var element = document.getElementById('timely-lightbox');
if (typeof(element) != 'undefined' && element != null) {
$('#timely-lightbox').fadeOut();
}
}
function insertAfter(f, n) {
var p = n.parentNode;
if (n.nextSibling) {
p.insertBefore(f, n.nextSibling);
} else {
p.appendChild(f);
}
}
function eventHandler() {
// prototype instance
}
eventHandler.prototype.Book = function() {
startBooking();
};
// everything is wrapped in the XD function to reduce namespace collisions
XD = function () {
var interval_id,
last_hash,
cache_bust = 1,
attached_callback,
window = context;
return {
postMessage: function (message, target_url, target) {
if (!target_url) {
return;
}
target = target || parent; // default to parent
if (window['postMessage']) {
// the browser supports window.postMessage, so call it with a targetOrigin
// set appropriately, based on the target_url parameter.
target['postMessage'](message, target_url.replace(/([^:]+:\/\/[^\/]+).*/, '$1'));
} else if (target_url) {
// the browser does not support window.postMessage, so use the window.location.hash fragment hack
target.location = target_url.replace(/#.*$/, '') + '#' + (+new Date) + (cache_bust++) + '&' + message;
}
},
receiveMessage: function (callback, source_origin) {
// browser supports window.postMessage
if (window['postMessage']) {
// bind the callback to the actual event associated with window.postMessage
if (callback) {
attached_callback = function (e) {
if ((typeof source_origin === 'string' && e.origin !== source_origin)
|| (Object.prototype.toString.call(source_origin) === "[object Function]" && source_origin(e.origin) === !1)) {
return !1;
}
callback(e);
};
}
if (window['addEventListener']) {
window[callback ? 'addEventListener' : 'removeEventListener']('message', attached_callback, !1);
} else {
window[callback ? 'attachEvent' : 'detachEvent']('onmessage', attached_callback);
}
} else {
// a polling loop is started & callback is called whenever the location.hash changes
interval_id && clearInterval(interval_id);
interval_id = null;
if (callback) {
interval_id = setInterval(function () {
var hash = document.location.hash,
re = /^#?\d+&/;
if (hash !== last_hash && re.test(hash)) {
last_hash = hash;
callback({ data: hash.replace(re, '') });
}
}, 100);
}
}
}
};
}();
// setup a callback to handle the dispatched MessageEvent. if window.postMessage is supported the passed
// event will have .data, .origin and .source properties. otherwise, it will only have the .data property.
XD.receiveMessage(function (message) {
if (message.data == 'close') {
var element = document.getElementById('timely-lightbox');
if (typeof (element) != 'undefined' && element != null) {
$('#timely-lightbox').show();
}
if (window.timelyBookFrame && window.timelyBookFrame.parentNode) window.timelyBookFrame.parentNode.removeChild(window.timelyBookFrame);
}
if (message.data == 'open' && window.timelyBookFrame) {
window.timelyBookFrame.style.display = 'block';
}
}, getDomain());
init();
// expose the BookButton API
return {
start: function() {
startBooking();
}
};
};
})();
So how can I run this javascript when I click the button?
Any help would be greatly appreciated!
You could create a script tag automatically if the button has been clicked.
document.getElementById('myButton').addEventListener('click', () => {
const script = document.createElement("script");
script.src = 'my-other-file.js';
document.head.appendChild(script);
})
<button id="myButton">Load JS File</button>

Data gets lost in a java script and .Net based chat app

This code has landed on my lap, and I don't have any clue what might be going on. The code is a Java Script in an ascx file as part of a chat system. The problem is that the chat content are lost after about 10 minutes. I don't know if this has anything to do with caching or not. I would like to know what might be causing the loss of chat content in this code.
<script type="text/javascript">
var roomid = '<%= ChatRoomID %>';
var status = "";
var msgTimer = "";
function StartTimers(sec) {
msgTimer = window.setInterval("DoRefresh()", sec);
}
function StopTimers() {
window.clearInterval(msgTimer);
msgTimer = "";
}
function SendMsg() {
if (!xmlrequest)
InitObject();
if (xmlrequest) {
var obj = document.getElementById("txtMsg");
if (obj != null && obj.value.trim().length > 0) {
StopTimers();
status = "completed";
var nowTime = new Date().getTime(); //Get now time as random
var params = "act=sendmsg&rid=" + roomid + "&gid=&msg=" + encodeURIComponent(obj.value) + "&st=" + status;
//xmlrequest.abort();
xmlrequest.onreadystatechange = SendMsg_Callback; //(GetBrowserVer() != "Firefox") ? (SendMsg_Callback) : (SendMsg_Callback());
xmlrequest.open("POST", "/site/function/chat.ashx?t=" + nowTime, false);
xmlrequest.setRequestHeader("If-Modified-Since", "0"); // Avoid the cache in IE
xmlrequest.setRequestHeader("Cache-Control", "no-cache");
xmlrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlrequest.setRequestHeader("Content-length", params.length);
xmlrequest.setRequestHeader("Connection", "close");
xmlrequest.send(params);
//xmlrequest.onreadystatechange = SendMsg_Callback; //(GetBrowserVer() != "Firefox") ? (SendMsg_Callback) : (SendMsg_Callback());
obj.value = "";
CharacterCount(obj);
obj.focus();
StartTimers(60);
}
}
}
function SendMsg_Callback() {
if (xmlrequest.readyState == 4 && (xmlrequest.status == 200 || xmlrequest.status == 0)) {
// sometimes, the completed status will equal zero in Firefox
}
}
function DoRefresh() {
StopTimers();
Refresh();
}
function Refresh() {
if (!xmlrequest)
InitObject();
if (xmlrequest) {
var nowTime = new Date().getTime(); //Get now time as random
var params = "act=refresh&rid=" + roomid + "&gid=&st=" + status;
//xmlrequest.abort();
xmlrequest.onreadystatechange = Refresh_Callback; //(GetBrowserVer() != "Firefox") ? (Refresh_Callback) : (Refresh_Callback());
xmlrequest.open("POST", "/site/function/chat.ashx?t=" + nowTime, true);
xmlrequest.setRequestHeader("If-Modified-Since", "0"); // Avoid the cache in IE
xmlrequest.setRequestHeader("Cache-Control", "no-cache");
xmlrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlrequest.setRequestHeader("Content-length", params.length);
//xmlrequest.setRequestHeader("Connection", "close");
xmlrequest.send(params);
xmlrequest.onreadystatechange = Refresh_Callback; //(GetBrowserVer() != "Firefox") ? (Refresh_Callback) : (Refresh_Callback());
}
}
function Refresh_Callback() {
if (xmlrequest.readyState == 4 && (xmlrequest.status == 200 || xmlrequest.status==0)) {
//if (xmlrequest.readyState == 4 && xmlrequest.status == 200) {
// Is ready
var response = xmlrequest.responseText;
//alert(response);
//document.write("<p>" + response + "</p>");
if (response != undefined && response.length > 0) {
var vals = null;
vals = response.split("<<<<<>>>>>");
if (vals == null || vals.length < 2) {
document.getElementById("msglist").value = response;
return;
}
/// The part one of response value is user list
var obj = document.getElementById("userlist");
if (obj != null && vals[0].length > 0) {
//alert(vals[0]);
obj.options.length = 0;
var options = vals[0].split(",");
for (i = 0; i < options.length; i++) {
obj.options.add(new Option(options[i], options[i]));
}
}
/// The part two of response value is chat message list
obj = document.getElementById("msglist");
if (obj != null && vals[1].length > 0) {
obj.innerHTML += vals[1] + "<br/>";
//obj.scrollIntoView("true");
obj.scrollTop = obj.scrollHeight;
}
/// The part three of response value is command or status
if (vals.length > 2) {
if (vals[2].toLowerCase() == "reload") {
//var sUrl = window.location.href;
//sUrl += (sUrl.indexOf("?") > 0) ? "&" : "?" + "r=t";
//window.location.href = sUrl; // window.location.href;
redirectURL(window.location.href);
}
else {
obj = document.getElementById("divStatus");
if (obj != null) {
obj.innerHTML = vals[2];
}
}
}
}
StartTimers(2500);
}
}
//////////////////////// End Call Ajax Function //////////////////////////////
function GetBrowserVer() {
var OsObject = "";
if (navigator.userAgent.toLowerCase().indexOf("msie") > 0) {
return "MSIE"; //IE
}
if (isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") > 0) {
return "Firefox"; //Firefox
}
if (isSafari = navigator.userAgent.toLowerCase().indexOf("safari") > 0) {
return "Safari"; //Safan
}
if (isCamino = navigator.userAgent.toLowerCase().indexOf("camino") > 0) {
return "Camino"; //Camino
}
if (isMozilla = navigator.userAgent.toLowerCase().indexOf("gecko") > 0) {
return "Gecko"; //Gecko
}
}
function getKeycode(evt) {
// Usually evt is indicated as keypress or other key events
var keycode = 0;
if (evt != undefined && evt != null && "which" in evt) {// NN4 & FF & Opera
keycode = evt.which;
}
else if (evt != undefined && evt != null && "keyCode" in evt) {// Safari & IE4+
keycode = evt.keyCode;
}
else if ("keyCode" in window.event) {// IE4+
keycode = window.event.keyCode;
}
else if ("which" in window.event) {
keycode = evt.which;
}
return keycode;
}
function DoSendMsg(e) {
//debugger
if (e.ctrlKey && getKeycode(e) == 13) {
SendMsg();
}
}
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
}
function redirectURL(url) {
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
var referLink = document.createElement('a');
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
} else {
window.location.href = url;
}
}
var CurrentUrl = '<%= Request.Url.ToString().ToLower() %>';
window.onload = function() {
if (CurrentUrl.indexOf("config_page_edit.aspx") < 0 && CurrentUrl.indexOf("config_page_preview.aspx") < 0) {
StartTimers(500);
}
}

Popunder script that works on all mobiles

I have tested around 15 different popunder scripts to find one that works on all mobiles. The following script is the best one I've found and works perfectly on my Galaxy S3 but annoyingly pops-over on a Galaxy S5. I need the script to popunder on any action on the screen, so that it opens in the background without interfering with the current page. This script has everything I need aside from the fact it behaves differently depending on what Android device it's run on. Can anyone please assist in editing this JavaScript code so it pops-under on all Android browsers and not just some?
Here is the code:
var puShown = false;
var PopWidth = 1370;
var PopHeight = 800;
var PopFocus = 0;
var _Top = null;
function GetWindowHeight() {
var myHeight = 0;
if (typeof(_Top.window.innerHeight) == 'number') {
myHeight = _Top.window.innerHeight;
} else if (_Top.document.documentElement && _Top.document.documentElement.clientHeight) {
myHeight = _Top.document.documentElement.clientHeight;
} else if (_Top.document.body && _Top.document.body.clientHeight) {
myHeight = _Top.document.body.clientHeight;
}
return myHeight;
}
function GetWindowWidth() {
var myWidth = 0;
if (typeof(_Top.window.innerWidth) == 'number') {
myWidth = _Top.window.innerWidth;
} else if (_Top.document.documentElement && _Top.document.documentElement.clientWidth) {
myWidth = _Top.document.documentElement.clientWidth;
} else if (_Top.document.body && _Top.document.body.clientWidth) {
myWidth = _Top.document.body.clientWidth;
}
return myWidth;
}
function GetWindowTop() {
return (_Top.window.screenTop != undefined) ? _Top.window.screenTop : _Top.window.screenY;
}
function GetWindowLeft() {
return (_Top.window.screenLeft != undefined) ? _Top.window.screenLeft : _Top.window.screenX;
}
function doOpen(url) {
var popURL = "about:blank"
var popID = "ad_" + Math.floor(89999999 * Math.random() + 10000000);
var pxLeft = 0;
var pxTop = 0;
pxLeft = (GetWindowLeft() + (GetWindowWidth() / 2) - (PopWidth / 2));
pxTop = (GetWindowTop() + (GetWindowHeight() / 2) - (PopHeight / 2));
if (puShown == true) {
return true;
}
var PopWin = _Top.window.open(popURL, popID, 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,top=' + pxTop + ',left=' + pxLeft + ',width=' + PopWidth + ',height=' + PopHeight);
if (PopWin) {
puShown = true;
if (PopFocus == 0) {
PopWin.blur();
if (navigator.userAgent.toLowerCase().indexOf("applewebkit") > -1) {
_Top.window.blur();
_Top.window.focus();
}
}
PopWin.Init = function(e) {
with(e) {
Params = e.Params;
Main = function() {
if (typeof window.mozPaintCount != "undefined") {
var x = window.open("about:blank");
x.close();
}
var popURL = Params.PopURL;
try {
opener.window.focus();
} catch (err) {}
window.location = popURL;
}
Main();
}
};
PopWin.Params = {
PopURL: url
}
PopWin.Init(PopWin);
}
return PopWin;
}
function setCookie(name, value, time) {
var expires = new Date();
expires.setTime(expires.getTime() + time);
document.cookie = name + '=' + value + '; path=/;' + '; expires=' + expires.toGMTString();
}
function getCookie(name) {
var cookies = document.cookie.toString().split('; ');
var cookie, c_name, c_value;
for (var n = 0; n < cookies.length; n++) {
cookie = cookies[n].split('=');
c_name = cookie[0];
c_value = cookie[1];
if (c_name == name) {
return c_value;
}
}
return null;
}
function initPu() {
_Top = self;
if (top != self) {
try {
if (top.document.location.toString())
_Top = top;
} catch (err) {}
}
if (document.attachEvent) {
document.attachEvent('onclick', checkTarget);
} else if (document.addEventListener) {
document.addEventListener('click', checkTarget, false);
}
}
function checkTarget(e) {
if (!getCookie('popundr')) {
var e = e || window.event;
var win = doOpen('http://www.mediamoby.com/4g9s0hc8/');
setCookie('popundr', 1, 24 * 60 * 60 * 1000);
}
}
initPu();

Categories