Getting a error when deleting a pdf file in Roxy Fileman - javascript
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.
Related
Window.showModalDialog() does not work in a for loop JavaScript
I am trying to introduce showModaldialog in a for loop, I have changed the names of the id's so that, being different, it can be opened as many times as the user requests: for (i = 0; i < number; i++) { cerrado=0; cerrado = window.showModalDialog(ventana, 'url' ,'nuevadiag'+id); if (cerrado==null){ i=numero; } } the problem is that it only opens once and nothing else, any ideas?, this is the jquery function of window.showModalDialog(): (function() { window.spawn = window.spawn || function(gen) { function continuer(verb, arg) { var result; try { result = generator[verb](arg); } catch (err) { return Promise.reject(err); } if (result.done) { return result.value; } else { return Promise.resolve(result.value).then(onFulfilled, onRejected); } } var generator = gen(); var onFulfilled = continuer.bind(continuer, 'next'); var onRejected = continuer.bind(continuer, 'throw'); return onFulfilled(); }; window.showModalDialog = window.showModalDialog || function(pantalla, url, arg, opt,id) { //documento= window.parent.parent.document; // alert(pantalla); documento= pantalla.document; // alert(documento.body); url = url || ''; //URL of a dialog arg = arg || null; //arguments to a dialog opt = opt || 'dialogWidth:300px;dialogHeight:200px;color:#ff6600;'; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles opt = opt+ ';color:#ff6600;'; var caller = ''; if(arguments.callee.caller != null ){ caller = arguments.callee.caller.toString(); } var dialog = documento.body.appendChild(document.createElement('dialog')); dialog.setAttribute('style', opt.replace(/dialog/gi, '')); dialog.setAttribute('id',id ); var idDialogClose="dialog-close"+id; var idDialogBody = 'dialog-body'; if( id!=undefined && id!=null && id!=''){ var idDialogBody ='dialog-body'+id; } dialog.innerHTML = '×<iframe id="'+idDialogBody+'" src="' + url + '" style="border: 0; width: 100%; height: 100%;border-top: 3px solid #ff6600;border-bottom: 3px solid #ff6600;border-left: 3px solid #ff6600;border-right: 3px solid #ff6600;margin-right: -10px;margin-bottom: -10px;"></iframe>'; documento.getElementById(idDialogBody).contentWindow.dialogArguments = arg; documento.getElementById(idDialogClose).addEventListener('click', function(e) { e.preventDefault(); dialog.close(); }); dialog.showModal(); //if using yield or async/await if(caller.indexOf('yield') >= 0 || caller.indexOf('await') >= 0) { return new Promise(function(resolve, reject) { dialog.addEventListener('close', function() { var returnValue = documento.getElementById(idDialogBody).contentWindow.returnValue; documento.body.removeChild(dialog); //resolve(returnValue); }); }); } //if using eval var isNext = false; var nextStmts = caller.split('\n').filter(function(stmt) { if(isNext || stmt.indexOf('showModalDialog(') >= 0) return isNext = true; return false; }); dialog.addEventListener('close', function() { var returnValue = documento.getElementById(idDialogBody).contentWindow.returnValue; documento.body.removeChild(dialog); alert('returnValue: '+returnValue); alert('nextStmts: '+nextStmts); alert('nextStmts[0]: '+nextStmts[0]); alert('nextStmts[1]: '+nextStmts[1]); nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue)); }); throw 'Execution stopped until showModalDialog is closed'; }; })(); thanks! BR.
js for newest chat message order
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; }```
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.
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); } }
Javascript in asp .Net
I'm getting WebResource error in my asp.Net page: var __pendingCallbacks = new Array(); Microsoft JScript runtime error: 'Array' is undefined I have no idea what might cause this to happen. Isn't Array part of Javascript itself? Any help would be appreciated. EDIT The problem is that this isn't code that I wrote, it's built into the page structure in asp.Net. EDIT The problem only occurs in IE9 and only when run in IE9 mode (not compatibility) Code: (This is dynamically generated code, sorry for the length. Problem is about halfway down) function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit) { this.eventTarget = eventTarget; this.eventArgument = eventArgument; this.validation = validation; this.validationGroup = validationGroup; this.actionUrl = actionUrl; this.trackFocus = trackFocus; this.clientSubmit = clientSubmit; } function WebForm_DoPostBackWithOptions(options) { var validationResult = true; if (options.validation) { if (typeof(Page_ClientValidate) == 'function') { validationResult = Page_ClientValidate(options.validationGroup); } } if (validationResult) { if ((typeof(options.actionUrl) != "undefined") && (options.actionUrl != null) && (options.actionUrl.length > 0)) { theForm.action = options.actionUrl; } if (options.trackFocus) { var lastFocus = theForm.elements["__LASTFOCUS"]; if ((typeof(lastFocus) != "undefined") && (lastFocus != null)) { if (typeof(document.activeElement) == "undefined") { lastFocus.value = options.eventTarget; } else { var active = document.activeElement; if ((typeof(active) != "undefined") && (active != null)) { if ((typeof(active.id) != "undefined") && (active.id != null) && (active.id.length > 0)) { lastFocus.value = active.id; } else if (typeof(active.name) != "undefined") { lastFocus.value = active.name; } } } } } } if (options.clientSubmit) { __doPostBack(options.eventTarget, options.eventArgument); } } var __pendingCallbacks = new Array(); var __synchronousCallBackIndex = -1; function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) { var postData = __theFormPostData + "__CALLBACKID=" + WebForm_EncodeCallback(eventTarget) + "&__CALLBACKPARAM=" + WebForm_EncodeCallback(eventArgument); if (theForm["__EVENTVALIDATION"]) { postData += "&__EVENTVALIDATION=" + WebForm_EncodeCallback(theForm["__EVENTVALIDATION"].value); } var xmlRequest,e; try { xmlRequest = new XMLHttpRequest(); } catch(e) { try { xmlRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { } } var setRequestHeaderMethodExists = true; try { setRequestHeaderMethodExists = (xmlRequest && xmlRequest.setRequestHeader); } catch(e) {} var callback = new Object(); callback.eventCallback = eventCallback; callback.context = context; callback.errorCallback = errorCallback; callback.async = useAsync; var callbackIndex = WebForm_FillFirstAvailableSlot(__pendingCallbacks, callback); if (!useAsync) { if (__synchronousCallBackIndex != -1) { __pendingCallbacks[__synchronousCallBackIndex] = null; } __synchronousCallBackIndex = callbackIndex; } if (setRequestHeaderMethodExists) { xmlRequest.onreadystatechange = WebForm_CallbackComplete; callback.xmlRequest = xmlRequest; xmlRequest.open("POST", theForm.action, true); xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); xmlRequest.send(postData); return; } callback.xmlRequest = new Object(); var callbackFrameID = "__CALLBACKFRAME" + callbackIndex; var xmlRequestFrame = document.frames[callbackFrameID]; if (!xmlRequestFrame) { xmlRequestFrame = document.createElement("IFRAME"); xmlRequestFrame.width = "1"; xmlRequestFrame.height = "1"; xmlRequestFrame.frameBorder = "0"; xmlRequestFrame.id = callbackFrameID; xmlRequestFrame.name = callbackFrameID; xmlRequestFrame.style.position = "absolute"; xmlRequestFrame.style.top = "-100px" xmlRequestFrame.style.left = "-100px"; try { if (callBackFrameUrl) { xmlRequestFrame.src = callBackFrameUrl; } } catch(e) {} document.body.appendChild(xmlRequestFrame); } var interval = window.setInterval(function() { xmlRequestFrame = document.frames[callbackFrameID]; if (xmlRequestFrame && xmlRequestFrame.document) { window.clearInterval(interval); xmlRequestFrame.document.write(""); xmlRequestFrame.document.close(); xmlRequestFrame.document.write('<html><body><form method="post"><input type="hidden" name="__CALLBACKLOADSCRIPT" value="t"></form></body></html>'); xmlRequestFrame.document.close(); xmlRequestFrame.document.forms[0].action = theForm.action; var count = __theFormPostCollection.length; var element; for (var i = 0; i < count; i++) { element = __theFormPostCollection[i]; if (element) { var fieldElement = xmlRequestFrame.document.createElement("INPUT"); fieldElement.type = "hidden"; fieldElement.name = element.name; fieldElement.value = element.value; xmlRequestFrame.document.forms[0].appendChild(fieldElement); } } var callbackIdFieldElement = xmlRequestFrame.document.createElement("INPUT"); callbackIdFieldElement.type = "hidden"; callbackIdFieldElement.name = "__CALLBACKID"; callbackIdFieldElement.value = eventTarget; xmlRequestFrame.document.forms[0].appendChild(callbackIdFieldElement); var callbackParamFieldElement = xmlRequestFrame.document.createElement("INPUT"); callbackParamFieldElement.type = "hidden"; callbackParamFieldElement.name = "__CALLBACKPARAM"; callbackParamFieldElement.value = eventArgument; xmlRequestFrame.document.forms[0].appendChild(callbackParamFieldElement); if (theForm["__EVENTVALIDATION"]) { var callbackValidationFieldElement = xmlRequestFrame.document.createElement("INPUT"); callbackValidationFieldElement.type = "hidden"; callbackValidationFieldElement.name = "__EVENTVALIDATION"; callbackValidationFieldElement.value = theForm["__EVENTVALIDATION"].value; xmlRequestFrame.document.forms[0].appendChild(callbackValidationFieldElement); } var callbackIndexFieldElement = xmlRequestFrame.document.createElement("INPUT"); callbackIndexFieldElement.type = "hidden"; callbackIndexFieldElement.name = "__CALLBACKINDEX"; callbackIndexFieldElement.value = callbackIndex; xmlRequestFrame.document.forms[0].appendChild(callbackIndexFieldElement); xmlRequestFrame.document.forms[0].submit(); } }, 10); }
This happens because we have this setup <collapsible panel> <iframe> <script> </script> </iframe> </collapsible panel> When the page loads, the panel being shown forces the script inside the iframe to be dragged through the DOM before the javascript libraries are loaded. This seems to be a change in that was made for IE9. I have yet to fine a way around this issue but at least I know the cause. A temporary workaround is to force the compatibility of the page to IE8 using a meta tag in case anybody else runs into this issue.
The problem was fixed when I removed the SRC attribute from the iframe and I added onOpen event to jQuery's dialog: open: function(){ document.getElementById("iframename").src = "page.aspx"; }