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);
}
}
Related
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.
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;
}```
I want to delete the file after i downloaded it from the server, but the delete method in service executes first even if i place it below the line of download file this is my code:
generateClearanceExcel(): void {
if (this.selectedIds.length > 0) {
var departureDate = prompt("Please enter departure date.", "");
if (departureDate !== null && departureDate !== "") {
this.generating = true;
this.clearanceService.generateClearanceExcel(this.selectedIds, departureDate).subscribe(
result => {
this.generating = false;
window.location.href = "clearance/downloadreport/?fileName=" + result.fileName;
this.clearanceService.deleteFile(result.fileName).subscribe();
if (result.success == true) {
if (result.infos.length > 0) {
this.alertService.info(result.infos);
}
}
else {
this.alertService.error(result.errors);
}
}
);
}
}
}
TIA.
Lets try with timeout
generateClearanceExcel(): void {
if (this.selectedIds.length > 0) {
var departureDate = prompt("Please enter departure date.", "");
if (departureDate !== null && departureDate !== "") {
this.generating = true;
this.clearanceService.generateClearanceExcel(this.selectedIds, departureDate).subscribe(
result => {
this.generating = false;
window.location.href = "clearance/downloadreport/?fileName=" + result.fileName;
setTimeout(() => {
this.clearanceService.deleteFile(result.fileName).subscribe();
}, 3000);
setTimeout(function(){ }, 3000);
if (result.success == true) {
if (result.infos.length > 0) {
this.alertService.info(result.infos);
}
}
else {
this.alertService.error(result.errors);
}
}
);
}
}
}
You should place the delete method inside the condition of success of download.
generateClearanceExcel(): void {
if (this.selectedIds.length > 0) {
var departureDate = prompt("Please enter departure date.", "");
if (departureDate !== null && departureDate !== "") {
this.generating = true;
this.clearanceService.generateClearanceExcel(this.selectedIds, departureDate).subscribe(
result => {
this.generating = false;
window.location.href = "clearance/downloadreport/?fileName=" + result.fileName;
if (result.success == true) {
this.clearanceService.deleteFile(result.fileName).subscribe();
if (result.infos.length > 0) {
this.alertService.info(result.infos);
}
}
else {
this.alertService.error(result.errors);
}
}
);
}
}
}
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();
I am trying to re-size my iframe according to the content size. After a lot of googling, I found out a way to perform it using hash tags in the url.Here is the link to the reference document. I am getting an error like TypeError: frameId is undefined. I suspect that my guest or original page returns the frameId as null. Why is it happening so?
I am testing it in the localhost. I use two Yii Sites for testing this.
This is my framed view.
<?php
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/frame.js');?>
<script type="text/javascript">
window.onload = function(event) {
window.setInterval(publishHeight, 300);
}
</script>
<div>
<div><?php echo CHtml::button('Book Now', array('submit' => array('controller/action','param1'=>$param1,'param2'=>$param2))); ?></div>
My host page is like this
<?php
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/FrameManager.js');?>
<iframe src="http://localhost/mysite/controller/action?param1=7¶m2=20" frameborder="0"scrolling="no" onload="FrameManager.registerFrame(this)"></iframe>
This is my frame.js
function publishHeight() {
if (window.location.hash.length == 0) return;
var frameId = getFrameId();
if (frameId == '') return;
var actualHeight = getBodyHeight();
var currentHeight = getViewPortHeight();
if (Math.abs(actualHeight - currentHeight) > 15) {
var hostUrl = window.location.hash.substring(1);
hostUrl += "#";
hostUrl += 'frameId=' + frameId;
hostUrl += '&';
hostUrl += 'height=' + actualHeight.toString();
window.top.location = hostUrl;
}
}
function getFrameId() {
var qs = parseQueryString(window.location.href);
var frameId = qs["frameId"];
var hashIndex = frameId.indexOf('#');
if (hashIndex > -1) {
frameId = frameId.substring(0, hashIndex);
}
return frameId;
}
function getBodyHeight() {
var height,
scrollHeight,
offsetHeight;
if (document.height) {
height = document.height;
} else if (document.body) {
if (document.body.scrollHeight) {
height = scrollHeight = document.body.scrollHeight;
}
if (document.body.offsetHeight) {
height = offsetHeight = document.body.offsetHeight;
}
if (scrollHeight && offsetHeight) {
height = Math.max(scrollHeight, offsetHeight);
}
}
return height;
}
function getViewPortHeight() {
var height = 0;
if (window.innerHeight) {
height = window.innerHeight - 18;
} else if ((document.documentElement) && (document.documentElement.clientHeight)) {
height = document.documentElement.clientHeight;
} else if ((document.body) && (document.body.clientHeight)) {
height = document.body.clientHeight;
}
return height;
}
function parseQueryString(url) {
url = new String(url);
var queryStringValues = new Object(),
querystring = url.substring((url.indexOf('?') + 1), url.length),
querystringSplit = querystring.split('&');
for (i = 0; i < querystringSplit.length; i++) {
var pair = querystringSplit[i].split('='),
name = pair[0],
value = pair[1];
queryStringValues[name] = value;
}
return queryStringValues;
}
This is my FrameManager.js
var FrameManager = {
currentFrameId : '',
currentFrameHeight : 0,
lastFrameId : '',
lastFrameHeight : 0,
resizeTimerId : null,
init: function() {
if (FrameManager.resizeTimerId == null) {
FrameManager.resizeTimerId = window.setInterval(FrameManager.resizeFrames, 500);
}
},
resizeFrames: function() {
FrameManager.retrieveFrameIdAndHeight();
if ((FrameManager.currentFrameId != FrameManager.lastFrameId) || (FrameManager.currentFrameHeight != FrameManager.lastFrameHeight)) {
var iframe = document.getElementById(FrameManager.currentFrameId.toString());
if (iframe == null) return;
iframe.style.height = FrameManager.currentFrameHeight.toString() + "px";
FrameManager.lastFrameId = FrameManager.currentFrameId;
FrameManager.lastFrameHeight = FrameManager.currentFrameHeight;
window.location.hash = '';
}
},
retrieveFrameIdAndHeight: function() {
if (window.location.hash.length == 0) return;
var hashValue = window.location.hash.substring(1);
if ((hashValue == null) || (hashValue.length == 0)) return;
var pairs = hashValue.split('&');
if ((pairs != null) && (pairs.length > 0)) {
for(var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if ((pair != null) && (pair.length > 0)) {
if (pair[0] == 'frameId') {
if ((pair[1] != null) && (pair[1].length > 0)) {
FrameManager.currentFrameId = pair[1];
}
} else if (pair[0] == 'height') {
var height = parseInt(pair[1]);
if (!isNaN(height)) {
FrameManager.currentFrameHeight = height;
FrameManager.currentFrameHeight += 15;
}
}
}
}
}
},
registerFrame: function(frame) {
var currentLocation = location.href;
var hashIndex = currentLocation.indexOf('#');
if (hashIndex > -1) {
currentLocation = currentLocation.substring(0, hashIndex);
}
frame.contentWindow.location = frame.src + '?frameId=' + frame.id + '#' + currentLocation;
}
};
window.setTimeout(FrameManager.init, 300);
I found out the problem. The problem was with my parseQueryString function and my host url. Actually inorder to get the frameId, i need to query the string diffrently as my url contains more parameters compared to the url given in reference. So i need to change the ParseQueryString function like this
querystring = url.substring((url.indexOf('?') + 22), url.length),
which will give my frameId eventually. The real problem was my poor knowledge in java script. Anyway got the answer.Thank you all.