Is it possible to serialize an Ace Session object? - javascript

I'd like to serialize and store Ace Session objects, so I can open a "File" and restore everything, value, selection, cursor position, mode, etc.
I've tried JSON.stringify(session) and it throws a circular error.
Any ideas?

the simplest version would be
var session = editor.session
state = {}
state.value = session.getValue();
state.selection = session.selection.toJSON()
state.options = session.getOptions()
state.mode = session.getMode().$id
state.folds = session.getAllFolds().map(function(fold) {
return {
start : fold.start,
end : fold.end,
placeholder : fold.placeholder
};
});
state.scrollTop = session.getScrollTop()
state.scrollLeft = session.getScrollLeft()
JSON.stringify(state)
and to restore
session.setValue(state.value)
session.selection.fromJSON(state.selection)
session.setOptions(state.options)
session.setMode(state.mode)
try {
state.folds.forEach(function(fold){
session.addFold(fold.placeholder,
Range.fromPoints(fold.start, fold.end));
});
} catch(e) {}
session.setScrollTop(state.scrollTop)
session.setScrollTop(state.scrollLeft)
this doesn't cover restoring undomanager which is doable but a little trickier. you can try to bump this issue https://github.com/ajaxorg/ace/issues/1452

My solution combined from 3 sources:
https://stackoverflow.com/a/20404474/630169
https://stackoverflow.com/a/28260919/630169
https://stackoverflow.com/a/34311510/630169
Moved session serialization code to a separate module:
editor-session.js:
var ace = require('brace');
var Range = ace.acequire('ace/range').Range;
var filterHistory = function(deltas) {
return deltas.filter(function (d) {
return d.group != "fold";
});
};
/** #param {AceAjax.Editor} editor */
function sessionToJson(editor)
{
return {
content: editor.getSession().getValue(),
selection: editor.getSelection().toJSON(),
options: editor.getOptions(),
mode: editor.session.getMode().$id,
scrollTop: editor.session.getScrollTop(),
scrollLeft: editor.session.getScrollLeft(),
history: {
undo: editor.session.getUndoManager().$undoStack.map(filterHistory),
redo: editor.session.getUndoManager().$undoStack.map(filterHistory)
},
folds: editor.session.getAllFolds().map(function(fold) {
return {
start : fold.start,
end : fold.end,
placeholder : fold.placeholder
};
})
}
}
/** #param {AceAjax.Editor} editor */
function jsonToSession(editor, state)
{
editor.session.setValue(state.content);
editor.selection.fromJSON(state.selection);
editor.session.setOptions(state.options);
editor.session.setMode(state.mode);
editor.session.setScrollTop(state.scrollTop);
editor.session.setScrollLeft(state.scrollLeft);
editor.session.$undoManager.$undoStack = state.history.undo;
editor.session.$undoManager.$redoStack = state.history.redo;
try {
state.folds.forEach(function(fold) {
editor.session.addFold(fold.placeholder, Range.fromPoints(fold.start, fold.end));
});
} catch(e) {console.log('Fold exception: ' + e)}
}
module.exports.sessionToJson = sessionToJson;
module.exports.jsonToSession = jsonToSession;
Browser side JS: processed by browserify
var ace = require('brace');
var state = require('./editor-session');
var editor = ace.edit('web-editor');
...
function saveEditorSession() {
localStorage.setItem('editorSession', JSON.stringify(state.sessionToJson(editor)));
}
editor.getSession().on("change", function () {
textarea.value = editor.getSession().getValue();
// Save editor session to localStorage
saveEditorSession();
// Send editor content to backend
ajax.saveContent(textarea.value, function (response) { });
});
editor.getSession().selection.on('changeSelection', saveEditorSession);
editor.getSession().selection.on('changeCursor', saveEditorSession);
editor.getSession().on('changeFold', saveEditorSession);
editor.getSession().on('changeScrollLeft', saveEditorSession);
editor.getSession().on('changeScrollTop', saveEditorSession);

Related

Browser Full screen feature

Hi I have the below page where you simply click the button Full screen and the page browser takes up the full screen, the navigation controls are also hidden to - which is what I like. However if you page refresh (or in my case my page refreshes every 5 minutes) the navigation controls return and it is no longer the view as previous. How can I solve this so that when it refreshed the navigation etc doesn't return and it remains full screen?
<html>
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" />
<script src="screenfull.js"></script>
<script>
$(function () {
$('#supported').text('Supported/allowed: ' + !!screenfull.enabled);
if (!screenfull.enabled) {
return false;
}
$('#request').click(function () {
screenfull.request($('#container')[0]);
// does not require jQuery, can be used like this too:
// screenfull.request(document.getElementById('container'));
});
$('#exit').click(function () {
screenfull.exit();
});
function fullscreenchange() {
var elem = screenfull.element;
$('#status').text('Is fullscreen: ' + screenfull.isFullscreen);
if (elem) {
$('#element').text('Element: ' + elem.localName + (elem.id ? '#' + elem.id : ''));
}
if (!screenfull.isFullscreen) {
$('#external-iframe').remove();
document.body.style.overflow = 'hidden';
}
}
document.addEventListener(screenfull.raw.fullscreenchange, fullscreenchange);
// set the initial values
fullscreenchange();
});
</script>
<button id="request"><i class="fa fa-arrows-alt"></i> Request</button>
<button id="exit">Exit</button>
</body>
(function () {
'use strict';
var isCommonjs = typeof module !== 'undefined' && module.exports;
var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element;
var fn = (function () {
var val;
var valLength;
var fnMap = [
[
'requestFullscreen',
'exitFullscreen',
'fullscreenElement',
'fullscreenEnabled',
'fullscreenchange',
'fullscreenerror'
],
// new WebKit
[
'webkitRequestFullscreen',
'webkitExitFullscreen',
'webkitFullscreenElement',
'webkitFullscreenEnabled',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
// old WebKit (Safari 5.1)
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitCurrentFullScreenElement',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozFullScreenElement',
'mozFullScreenEnabled',
'mozfullscreenchange',
'mozfullscreenerror'
],
[
'msRequestFullscreen',
'msExitFullscreen',
'msFullscreenElement',
'msFullscreenEnabled',
'MSFullscreenChange',
'MSFullscreenError'
]
];
var i = 0;
var l = fnMap.length;
var ret = {};
for (; i < l; i++) {
val = fnMap[i];
if (val && val[1] in document) {
for (i = 0, valLength = val.length; i < valLength; i++) {
ret[fnMap[0][i]] = val[i];
}
return ret;
}
}
return false;
})();
var screenfull = {
request: function (elem) {
var request = fn.requestFullscreen;
elem = elem || document.documentElement;
// Work around Safari 5.1 bug: reports support for
// keyboard in fullscreen even though it doesn't.
// Browser sniffing, since the alternative with
// setTimeout is even worse.
if (/5\.1[\.\d]* Safari/.test(navigator.userAgent)) {
elem[request]();
} else {
elem[request](keyboardAllowed && Element.ALLOW_KEYBOARD_INPUT);
}
},
exit: function () {
document[fn.exitFullscreen]();
},
toggle: function (elem) {
if (this.isFullscreen) {
this.exit();
} else {
this.request(elem);
}
},
raw: fn
};
if (!fn) {
if (isCommonjs) {
module.exports = false;
} else {
window.screenfull = false;
}
return;
}
Object.defineProperties(screenfull, {
isFullscreen: {
get: function () {
return Boolean(document[fn.fullscreenElement]);
}
},
element: {
enumerable: true,
get: function () {
return document[fn.fullscreenElement];
}
},
enabled: {
enumerable: true,
get: function () {
// Coerce to boolean in case of old WebKit
return Boolean(document[fn.fullscreenEnabled]);
}
}
});
if (isCommonjs) {
module.exports = screenfull;
} else {
window.screenfull = screenfull;
}
})();
Online Demo : https://plnkr.co/edit/zx0rXwXpJbWdMvh3HQ25?p=preview
Make onepage website (ajax) (no refresh) Use history pushstate to save all your links so you can use history navigation and change your URL. (most of time I use this approach.)
Or you can use localstorage to save state.
Theoretically You can store an indication of what was the previews state (full-screen / normal) in the browser storage.
Then on page load, read the stored value and activate full-screen if necessary.
However, modern browsers require this to be an interactive user action (not automatically via script on load)
If you try to automate this, you'll get these type of warnings in the browser's console:
Alternatives
Avoid full refreshes
Workaround using custom browser extension to restore the fullscreen state

selectize.js questions about a no result plugin and allowing default behaviour on link

I am using selectize for an auto suggest field, and i have used one of the no_results plugins to show a link when there is no result, and this works great for the most part, but i have a few dramas i am just not sure how to get around
I have two things i need to get help with
1st most important - How to pass variables to the plugin
I have multiple instances of selectize on the several pages, so i need to pass the vars hr_link and hr_label to the plugin so i don't have to recreate the plugin 30 times with just the those vars different
2nd - Allow link to be clicked, bypassing default behaviour
To get the links to be clickable i have used the onmousedown() and touchstart() but is there a better way to re-enable the default click on just this link in the results box.
I have spent a lot of time researching these items, so I don't think it is a duplicate
// The Plugin
Selectize.define('header_no_results', function( options ) {
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
var ignoreKeys = [KEY_LEFT, KEY_UP, KEY_RIGHT, KEY_DOWN];
var self = this;
var hr_link = 'http://link_to_info.com';
var hr_label = 'country';
options = $.extend({
message: ' No results found: click here to add a'+hr_label,
html: function(data) {
return '<div class="selectize-dropdown-content">' + data.message + '</div>';
}
}, options );
self.on('type', function() {
var message = 'Not Found: click here Add a '+hr_label;
if (!self.hasOptions) {
self.$empty_results_container.html(message).show();
} else {
self.$empty_results_container.hide();
}
});
self.onKeyUp = (function() {
var original = self.onKeyUp;
return function ( e ) {
if (ignoreKeys.indexOf(e.keyCode) > -1) return;
self.isOpen = false;
original.apply( self, arguments );
}
})();
self.onBlur = (function () {
var original = self.onBlur;
return function () {
original.apply( self, arguments );
self.$empty_results_container.hide();
};
})();
self.setup = (function() {
var original = self.setup;
return function() {
original.apply( self, arguments);
self.$empty_results_container = $(
options.html($.extend({
classNames: self.$input.attr( 'class' )
}, options))
);
self.$empty_results_container.hide();
self.$dropdown.append(self.$empty_results_container);
};
})();
});
// the function calling the plugin
$('#companyLinks').selectize({
valueField: 'id',
labelField: 'display',
searchField: 'display',
maxItems: 1,
options: [],
create: false,
onItemAdd: function(value){
window.location.href = 'http://my_link.com/'+value;
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'http://link.com/get/list',
type: 'GET',
dataType: 'json',
data: {
q: query
},
error: function() {
callback();
},
success: function(res) {
callback(res);
//window.open($(res).val(), '_self');
}
});
},
plugins: ['header_no_results']
});
The solution to pass the var was not all that hard after all just had to look in the right place, and there is further info here
In the function we need to change out
plugins: ['header_no_results']
with
plugins: { "header_no_results": {
link : "page/location",
} }
then we can retrieve link and declare the var we needed in the plugin by
var hr_link = options.link;

Jquery how clean formData object in my own upload plugin

I tried to create my own plugin for upload files via ajax.
If the page where there is the input file is reloaded after upload It seems to work good.
If the page where there is the input file is NOT reloaded after upload (because was reloaded only ajax content) There are problems with IE and Chrome because the files to upload are appended to previous just uploaded (with firefox is ok).
I tried to fix it by cleaning the input file after the first upload but in this way then with IE and Chrome I can no longer upload other files.
MY FIX
complete: function () {
defaults.onFinish.call(this);
// If page where is the input file not reloaded
// after upload files IE and Chrome not working
$this.replaceWith($this.val('').clone(true));
$this.val('');
}
In truth I would clean the formData object after every upload but I haven't been able to do it
MY PLUGIN
;(function ($, window, document, undefined) {
// Function-level strict mode syntax
'use strict';
$.fn.ajaxUpload = function(options) {
var defaults = {
num_files : 0,
max_files : 2,
max_concurrent : 10,
max_filesize : 1024 * 4096,
php_max_size : 1024 * 8192,
allowed_types : ['jpeg','jpg'],
ajax_url : 'action.php',
var_name : 'file',
extra_fields : {},
onFinish : function() {}
};
var options = $.extend(defaults, options);
return this.each(function() {
var $this = $(this);
$this.on('change', function() {
var files = $this[0].files;
var len = files.length;
var items = 0;
var diff_files = parseInt(defaults.max_files - defaults.num_files - len);
if(diff_files < 0) {
return false;
}
if(!maxUploadFiles(len, defaults.max_concurrent)) {
return false;
}
var formdata = new FormData();
jQuery.each(files, function(i, file) {
if(!isOverSized(file, defaults.max_filesize)) {
return false;
}
if(!isAllowedTypes(file, defaults.allowed_types)) {
return false;
}
if(!totalFilesSize(file, defaults.php_max_size)) {
return false;
}
formdata.append(defaults.var_name + '['+i+']', file);
items++;
});
// Append extra data to formdata
$.each(defaults.extra_fields, function(name, value) {
formdata.append(name, value);
});
// Check that files have passed all test
if (len != items) { return false; }
$.ajax({
url: defaults.ajax_url,
data: formdata,
cache: false,
contentType: false,
processData: false,
type: 'POST',
beforeSend: function () {
},
success: function(data) {
totalSize = 0;
},
complete: function () {
defaults.onFinish.call(this);
// If page where is the input file not reloaded
// after upload files IE and Chrome not working
//$this.replaceWith($this.val('').clone(true));
//$this.val('');
}
});
});
});
};
var totalSize = 0;
function totalFilesSize(file, php_max_size) {
totalSize += file.size;
if(totalSize > php_max_size) {
totalSize = 0;
return false;
}
return true;
}
function maxUploadFiles(len, max_concurrent) {
if(len > max_concurrent) {
return false;
}
return true;
}
function isAllowedTypes(file, allowed_types) {
var ext = file.name.split('.').pop().toLowerCase();
if(jQuery.inArray(ext, allowed_types) < 0) {
return false;
}
return true;
}
function isOverSized(file, max_filesize) {
if(file.size > max_filesize) {
return false;
}
return true;
}
})(jQuery, window, document);
According to you that changes should I do to solve my problem?
Thank you
EDIT
I add this line on complete, and It seems to work
$this.val('');
$this.wrap('<form>').parent('form').trigger('reset');
$this.unwrap();
$this.replaceWith($this.clone());
The problem with your plugin is that you keep a reference to the original input with $this and then tried to replace it with a clone. Because you are cloning is better to get a new reference each time so you should unbind and bind .
(function ($, window, document, undefined) {
// Function-level strict mode syntax
'use strict';
$.fn.ajaxUpload = function (options) {
var defaults = {
num_files: 0,
max_files: 2,
max_concurrent: 10,
max_filesize: 1024 * 4096,
php_max_size: 1024 * 8192,
allowed_types: ['jpeg', 'jpg'],
ajax_url: 'action.php',
var_name: 'file',
extra_fields: {},
onFinish: function () {}
};
var options = $.extend(defaults, options);
var bindInput = function (elem) {
var element = $(elem),
bindFunc = function (evt) {
var files = evt.currentTarget.files;
var len = files.length;
var items = 0;
var diff_files = parseInt(defaults.max_files - defaults.num_files - len);
if (diff_files < 0) {
return false;
}
if (!maxUploadFiles(len, defaults.max_concurrent)) {
return false;
}
var formdata = new FormData();
jQuery.each(files, function (i, file) {
if (!isOverSized(file, defaults.max_filesize)) {
return false;
}
if (!isAllowedTypes(file, defaults.allowed_types)) {
return false;
}
if (!totalFilesSize(file, defaults.php_max_size)) {
return false;
}
formdata.append(defaults.var_name + '[' + i + ']', file);
items++;
});
// Append extra data to formdata
$.each(defaults.extra_fields, function (name, value) {
formdata.append(name, value);
});
// Check that files have passed all test
if (len != items) {
return false;
}
$.ajax({
url: defaults.ajax_url,
data: formdata,
cache: false,
contentType: false,
processData: false,
type: 'POST',
beforeSend: function () {},
success: function (data) {
totalSize = 0;
},
complete: function () {
defaults.onFinish.call(this);
var previous = $(evt.currentTarget);
previous.off('change', bindFunc);
var newElem = previous.val('').clone(true)
previous.replaceWith(newElem);
bindInput(newElem);
}
});
};
element.on('change', bindFunc);
};
return this.each(function () {
bindInput(this)
});
};
var totalSize = 0;
function totalFilesSize(file, php_max_size) {
totalSize += file.size;
if (totalSize > php_max_size) {
totalSize = 0;
return false;
}
return true;
}
function maxUploadFiles(len, max_concurrent) {
if (len > max_concurrent) {
return false;
}
return true;
}
function isAllowedTypes(file, allowed_types) {
var ext = file.name.split('.').pop().toLowerCase();
if (jQuery.inArray(ext, allowed_types) < 0) {
return false;
}
return true;
}
function isOverSized(file, max_filesize) {
if (file.size > max_filesize) {
return false;
}
return true;
}
})(jQuery, window, document);
{Edit}
The problem that originate your question is the nightmare of every file upload plugin developer. As you are developing a plugin you should be aware that the input tag may contain other styles and event handlers set by the consumer of the plugin that you must preserve or you will break existing functionality.
For security reasons the value of the input type file cannot be changed with javascript. There are a lot of answers in SO about that. Search for clear+input+file and see for yourself, the most remarkable is this Clearing <input type='file' /> using jQuery
As you can see there are basically two choices:
Clone the input and call val('') before cloning (calling jQuery $(input).val('') is not the same that calling input.value = '').
The problems of this approach is for example that in IE this event is called twice when clearing the file input and you must be carefull about releasing memory and references to the input being replaced while preserving current styles and event handlers that were not set by your plugin
The second is better but has issues as well. Wrap your input in a form tag and call the form's reset method.
input.wrap('<form>').parent('form').trigger('reset');
input.unwrap();
Check the docs about the sintax of the form tag and you will see the following quote
Note: It's strictly forbidden to nest a form inside another form. Doing so can behave in an unpredictable way that will depend on which browser the user is using.
The main reasoning behind that is that your plugin can be applied to an input tag that is already inside a form leaving you with invalid html so you must wrap the form call the reset method and remove this form right away. Also remember that forms may have visual styles applied to them breaking the user interface if you leave them around.
In the second alternative is easier to fix your code. Just change the complete callback like this. No cloning is needed in this case.
complete: function () {
defaults.onFinish.call(this);
$this.wrap('<form>').parent('form').trigger('reset');
$this.unwrap();
}
This changes should happen so fast that the users will not notice them. I tested with 1000 elements around and no visual glitches were visible.

AngularJs+Bootstrap+Typehead+Ajax is working only if i put alert box but only in chrome

i am using bootsrap typehead with angularjs given at this link http://angular-ui.github.io/bootstrap/
In my controller
$scope.getUser = function(val) {
//alert("hi");
return $http.get('user/getUserNames.do', {
params: {
userName: val,
}
}).then(function(response){
return response.data;
});
};
my html code
<input type="text" ng-model="asyncSelected" typeahead-wait-ms="300" typeahead="user for user in getUser($viewValue)" class="form-control">
if remove the alert the typehead will not work
if i keep the alert the typehead will work only in chrome
if i place a break point at "return $http.get('user/getUserNames.do'" and step out using
fire bug it works in firefox
i am receiving the data in this formate ['name1','name2'] from server
some one please help
thanks in advance
thats because the time taken to close the alert the async data is recieved. you should store the data on $scope rather then calling a function on $scope
$scope.users= {};
$scope.getUser = function(val) {
return $http.get('user/getUserNames.do', {
params: {
userName: val,
}
}).then(function(response){
$scope.users= response.data;
});
};
html
<input type="text" ng-model="asyncSelected" ng-change="getUser($viewValue)"
typeahead-wait-ms="300" typeahead="user for user in users" class="form-control">
your cods logic is incorrect,you cant return data like that from a async function, that need time to complete,
dont return anything from this getUser function. you have 2 option :
1 - store the responce.data in a global variable to be used later
$scope.users = [];
$scope.getUser = function (val) {
$http.get('user/getUserNames.do', {
params: {
userName: val
}
}).then(function (response) {
$scope.users.push(response.data);
});
};
2 - call another function when get function is complete to handle the data recived
$scope.getUser = function (val) {
$http.get('user/getUserNames.do', {
params: {
userName: val
}
}).then(function (response) {
$scope.userLoaded(response.data);
});
};
By the simple hack in angular-ui-bootstrap i solved the problem
before..........
var getMatchesAsync = function(inputValue) {
var locals = {$viewValue: inputValue};
isLoadingSetter(originalScope, true);
$q.when(parserResult.source(originalScope, locals)).then(function(matches) {
//it might happen that several async queries were in progress if a user were typing fast
//but we are interested only in responses that correspond to the current view value
var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
if (onCurrentRequest && hasFocus) {
if (matches.length > 0) {
scope.activeIdx = focusFirst ? 0 : -1;
scope.matches.length = 0;
//transform labels
for(var i=0; i<matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
id: getMatchId(i),
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = inputValue;
//position pop-up with matches - we need to re-calculate its position each time we are opening a window
//with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
//due to other elements being rendered
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
element.attr('aria-expanded', true);
} else {
resetMatches();
}
}
if (onCurrentRequest) {
isLoadingSetter(originalScope, false);
}
}, function(){
resetMatches();
isLoadingSetter(originalScope, false);
});
};
i just removed '&& hasFocus' this sipneet from the code
after ........
var getMatchesAsync = function(inputValue) {
var locals = {$viewValue: inputValue};
isLoadingSetter(originalScope, true);
$q.when(parserResult.source(originalScope, locals)).then(function(matches) {
//it might happen that several async queries were in progress if a user were typing fast
//but we are interested only in responses that correspond to the current view value
var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
if (onCurrentRequest) {
if (matches.length > 0) {
scope.activeIdx = focusFirst ? 0 : -1;
scope.matches.length = 0;
//transform labels
for(var i=0; i<matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
id: getMatchId(i),
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = inputValue;
//position pop-up with matches - we need to re-calculate its position each time we are opening a window
//with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
//due to other elements being rendered
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
element.attr('aria-expanded', true);
} else {
resetMatches();
}
}
if (onCurrentRequest) {
isLoadingSetter(originalScope, false);
}
}, function(){
resetMatches();
isLoadingSetter(originalScope, false);
});
};

Error 0x8007000e (NS_ERROR_OUT_OF_MEMORY)

I'm working on an addon to a forum and I get this error:
Error: Component returned failure code: 0x8007000e (NS_ERROR_OUT_OF_MEMORY) [nsIXPCComponents_Utils.evalInSandbox]
I read that the error means that the script goes into infinite loop until it fills the sandbox.
apparently the js file that leads to this error is script-compiler.js
this is the script:
var ddplus_gmCompiler={
// getUrlContents adapted from Greasemonkey Compiler
// http://www.letitblog.com/code/python/greasemonkey.py.txt
// used under GPL permission
//
// most everything else below based heavily off of Greasemonkey
// http://greasemonkey.mozdev.org/
// used under GPL permission
getUrlContents: function(aUrl){
var ioService=Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var scriptableStream=Components
.classes["#mozilla.org/scriptableinputstream;1"]
.getService(Components.interfaces.nsIScriptableInputStream);
var channel=ioService.newChannel(aUrl, null, null);
var input=channel.open();
scriptableStream.init(input);
var str=scriptableStream.read(input.available());
scriptableStream.close();
input.close();
return str;
},
isGreasemonkeyable: function(url) {
var scheme=Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService)
.extractScheme(url);
return (
(scheme == "http" || scheme == "https" || scheme == "file") &&
!/hiddenWindow\.html$/.test(url)
);
},
contentLoad: function(e) {
var unsafeWin=e.target.defaultView;
if (unsafeWin.wrappedJSObject) unsafeWin=unsafeWin.wrappedJSObject;
var unsafeLoc=new XPCNativeWrapper(unsafeWin, "location").location;
var href=new XPCNativeWrapper(unsafeLoc, "href").href;
if (
ddplus_gmCompiler.isGreasemonkeyable(href)
&& ( /http:\/\/ddunlimited\.net/.test(href) )
&& true
) {
var script=ddplus_gmCompiler.getUrlContents(
'chrome://ddplus/content/ddplus.js'
);
ddplus_gmCompiler.injectScript(script, href, unsafeWin);
}
},
injectScript: function(script, url, unsafeContentWin) {
var sandbox, script, logger, storage, xmlhttpRequester;
var safeWin=new XPCNativeWrapper(unsafeContentWin);
sandbox=new Components.utils.Sandbox(safeWin);
var storage=new ddplus_ScriptStorage();
xmlhttpRequester=new ddplus_xmlhttpRequester(
unsafeContentWin, window//appSvc.hiddenDOMWindow
);
sandbox.window=safeWin;
sandbox.document=sandbox.window.document;
sandbox.unsafeWindow=unsafeContentWin;
// patch missing properties on xpcnw
sandbox.XPathResult=Components.interfaces.nsIDOMXPathResult;
// add our own APIs
sandbox.GM_addStyle=function(css) { ddplus_gmCompiler.addStyle(sandbox.document, css) };
sandbox.GM_setValue=ddplus_gmCompiler.hitch(storage, "setValue");
sandbox.GM_getValue=ddplus_gmCompiler.hitch(storage, "getValue");
// kick : aggiunta la funzione
sandbox.GM_remove=ddplus_gmCompiler.hitch(storage, "remove");
sandbox.GM_openInTab=ddplus_gmCompiler.hitch(this, "openInTab", unsafeContentWin);
sandbox.GM_xmlhttpRequest=ddplus_gmCompiler.hitch(
xmlhttpRequester, "contentStartRequest"
);
//unsupported
sandbox.GM_registerMenuCommand=function(){};
sandbox.GM_log=function(){};
sandbox.GM_getResourceURL=function(){};
sandbox.GM_getResourceText=function(){};
sandbox.__proto__=sandbox.window;
try {
this.evalInSandbox(
"(function(){"+script+"})()",
url,
sandbox);
} catch (e) {
var e2=new Error(typeof e=="string" ? e : e.message);
e2.fileName=script.filename;
e2.lineNumber=0;
//GM_logError(e2);
alert(e2);
}
},
evalInSandbox: function(code, codebase, sandbox) {
if (Components.utils && Components.utils.Sandbox) {
// DP beta+
Components.utils.evalInSandbox(code, sandbox);
} else if (Components.utils && Components.utils.evalInSandbox) {
// DP alphas
Components.utils.evalInSandbox(code, codebase, sandbox);
} else if (Sandbox) {
// 1.0.x
evalInSandbox(code, sandbox, codebase);
} else {
throw new Error("Could not create sandbox.");
}
},
openInTab: function(unsafeContentWin, url) {
var tabBrowser = getBrowser(), browser, isMyWindow = false;
for (var i = 0; browser = tabBrowser.browsers[i]; i++)
if (browser.contentWindow == unsafeContentWin) {
isMyWindow = true;
break;
}
if (!isMyWindow) return;
var loadInBackground, sendReferrer, referrer = null;
loadInBackground = tabBrowser.mPrefs.getBoolPref("browser.tabs.loadInBackground");
sendReferrer = tabBrowser.mPrefs.getIntPref("network.http.sendRefererHeader");
if (sendReferrer) {
var ios = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
referrer = ios.newURI(content.document.location.href, null, null);
}
tabBrowser.loadOneTab(url, referrer, null, null, loadInBackground);
},
hitch: function(obj, meth) {
var unsafeTop = new XPCNativeWrapper(unsafeContentWin, "top").top;
for (var i = 0; i < this.browserWindows.length; i++) {
this.browserWindows[i].openInTab(unsafeTop, url);
}
},
apiLeakCheck: function(allowedCaller) {
var stack=Components.stack;
var leaked=false;
do {
if (2==stack.language) {
if ('chrome'!=stack.filename.substr(0, 6) &&
allowedCaller!=stack.filename
) {
leaked=true;
break;
}
}
stack=stack.caller;
} while (stack);
return leaked;
},
hitch: function(obj, meth) {
if (!obj[meth]) {
throw "method '" + meth + "' does not exist on object '" + obj + "'";
}
var hitchCaller=Components.stack.caller.filename;
var staticArgs = Array.prototype.splice.call(arguments, 2, arguments.length);
return function() {
if (ddplus_gmCompiler.apiLeakCheck(hitchCaller)) {
return;
}
// make a copy of staticArgs (don't modify it because it gets reused for
// every invocation).
var args = staticArgs.concat();
// add all the new arguments
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
// invoke the original function with the correct this obj and the combined
// list of static and dynamic arguments.
return obj[meth].apply(obj, args);
};
},
addStyle:function(doc, css) {
var head, style;
head = doc.getElementsByTagName('head')[0];
if (!head) { return; }
style = doc.createElement('style');
style.type = 'text/css';
style.innerHTML = css;
head.appendChild(style);
},
onLoad: function() {
var appcontent=window.document.getElementById("appcontent");
if (appcontent && !appcontent.greased_ddplus_gmCompiler) {
appcontent.greased_ddplus_gmCompiler=true;
appcontent.addEventListener("DOMContentLoaded", ddplus_gmCompiler.contentLoad, false);
}
},
onUnLoad: function() {
//remove now unnecessary listeners
window.removeEventListener('load', ddplus_gmCompiler.onLoad, false);
window.removeEventListener('unload', ddplus_gmCompiler.onUnLoad, false);
window.document.getElementById("appcontent")
.removeEventListener("DOMContentLoaded", ddplus_gmCompiler.contentLoad, false);
},
}; //object ddplus_gmCompiler
function ddplus_ScriptStorage() {
this.prefMan=new ddplus_PrefManager();
}
ddplus_ScriptStorage.prototype.setValue = function(name, val) {
this.prefMan.setValue(name, val);
}
ddplus_ScriptStorage.prototype.getValue = function(name, defVal) {
return this.prefMan.getValue(name, defVal);
}
ddplus_ScriptStorage.prototype.remove = function(name) {
return this.prefMan.remove(name);
}
window.addEventListener('load', ddplus_gmCompiler.onLoad, false);
window.addEventListener('unload', ddplus_gmCompiler.onUnLoad, false);
The user script is massive and available in this gist.
To be able to see the error:
install the addon
go to the message board at http://ddunlimited.net/
open any thread and open click the reply link
The message will appear as soon as the reply page loads.
in practice is a tool created specifically for a forum ... with the functions targeted to simplify the daily actions of the moderator. Now the forum has changed domain and tried to make it compatible with the new forum. I'm editing the js file with a simple text editor. ettengo the error when I edit the script that I posted above. if you do not touch this script ... some functions disappear and are no longer present.
someone can help me? thank you very much: D
OK, reproducible after all. The error in this case has a bogus message, as this isn't actually an OOM condition, but evalInSandbox() receiving a notification from the JS engine that the script was aborted (due to it being unresponsive) and evalInSandbox() not being able to tell the difference.
The reason is an infinite loop in your code at line 425 (cont.):
var max = textArea.parentNode.parentNode.clientHeight;
while (max == textArea.parentNode.parentNode.clientHeight)
textArea.rows++;
This loop whill never abort as the condition will never get false.

Categories

Resources