GM_registerMenuCommand is not defined - javascript

everybody. I'm puzzled as to why I keep getting the error "GM_registerMenuCommand is not defined" when I try to run a userscript that I created. I have tried this in Firefox using Scriptish 1.0b9 and the latest version of Greasemonkey. I even disabled all addons except Scriptish to see if it was a conflict, but with no joy.
I'm including jQuery in my userscript using this template by Erik Vold. Before trying this template, I put the exact same code block in the template proposed by Joan Piedra and everything worked fine. Unfortunately, Piedra's template did not work in Chrome, which is something that I think is necessary, considering Chrome's growing userbase. The snippet that's throwing the error is below:
// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
var script = document.createElement("script");
script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js");
script.addEventListener('load', function() {
var script = document.createElement("script");
script.textContent = "(" + callback.toString() + ")();";
document.body.appendChild(script);
}, false);
document.body.appendChild(script);
}
// the guts of this userscript
function main() {
var isLevelupMove = false;
var isTutorMove = false;
var isTM = false;
var TMhead = $('#moves\\:machine');
var hasSecondEvo = false;
var hasFinalEvo1 = false;
var hasFinalEvo2 = false;
var header = $('.header-row').eq(1);
var TMmoves = new Array();
//This section deals with the user-defined colors
GM_registerMenuCommand("Color for pre-evolutionary-only moves", prevoColorPrompt);
GM_registerMenuCommand("Color for first evolution-only moves", evoColorPrompt);
if(localStorage.getItem('prevoColor') == null || localStorage.getItem('evoColor') == null)
{
localStorage.setItem('prevoColor', 'red');
localStorage.setItem('evoColor', 'orange');
}
var prevoColor = localStorage.getItem('prevoColor');
var evoColor = localStorage.getItem('evoColor');
function prevoColorPrompt()
{
var input = prompt("Please enter a desired 6-digit hex color-code for pre-evolutionary pokemon:")
localStorage.setItem('prevoColor', '#'+input);
}
function evoColorPrompt()
{
var input = prompt("Please enter the desired 6-digit hex color-code for first-evolution pokemon:")
localStorage.setItem('evoColor', '#'+input);
}
//This loop tests each 'th' element in a sample header row, determining how many Evos are currently present in the chart.
$('.header-row').eq(1).find('th').each(function(index)
{
if($(this).find('a').length != 0)
{
switch(index)
{
case 2:
hasSecondEvo = true;
break;
case 3:
hasFinalEvo1 = true;
break;
case 4:
hasFinalEvo2 = true;
break;
}
}
});
//All 'tr' siblings are TM moves, since it's the last section on the page
//This array puts only the names of the available TMs into the TMmoves array
TMhead.nextAll().each(function(index)
{
TMmoves.push($(this).children(":first").find('a').eq(0).html());
});
$('tr').each(function(index)
{
var moveName = $(this).children(":first").find('a').eq(0).html();
moveName = $.trim(moveName);
switch($(this).attr('id'))
{
case 'moves:level-up':
isLevelupMove = true;
break;
case 'moves:egg':
isLevelupMove = false;
break;
case 'moves:tutor':
isTutorMove = true;
case 'moves:machine':
isTM = true;
}
if(isLevelupMove || isTutorMove)
{
var babyMoveCell = $(this).find('td').eq(0);
babyMoveText = $.trim(babyMoveCell.html());
secondEvoCell = babyMoveCell.next();
secondEvoText = $.trim(secondEvoCell.html());
finalEvo1Cell = secondEvoCell.next();
finalEvo1Text = $.trim(finalEvo1Cell.html());
finalEvo2Cell = finalEvo1Cell.next();
finalEvo2Text = $.trim(finalEvo2Cell.html());
//This checks if evolutions have checkmarks
if(babyMoveText.length > 0)
{
if(hasSecondEvo && secondEvoText.length == 0 || hasFinalEvo1 && finalEvo1Text.length == 0 ||
hasFinalEvo2 && finalEvo2Text.length == 0)
{
//See if the move is a TM before proceeding
var tm = tmCheck(moveName);
if(!tm)
{
if(secondEvoText.length > 0)
{
babyMoveCell.css("color", evoColor);
secondEvoCell.css("color", evoColor);
babyMoveCell.prev().find('a').eq(0).css("color", evoColor); //highlights move name
}
else
{
babyMoveCell.css("color", prevoColor);
babyMoveCell.prev().find('a').eq(0).css("color", prevoColor);
}
}
}
}
else if(secondEvoText.length > 0)
{
if(hasFinalEvo1 && finalEvo1Text.length == 0 || hasFinalEvo2 && finalEvo2Text.length == 0)
{
var tm = tmCheck(moveName);
if(!tm)
{
secondEvoCell.css("color", evoColor);
babyMoveCell.prev().find('a').eq(0).css("color", evoColor);
}
}
}
}
});
function tmCheck(input)
{
var isTM = false;
//Iterate through TMmoves array to see if the input matches any entries
for(var i = 0; i < TMmoves.length; i++)
{
if(input == TMmoves[i])
{
isTM = true;
break;
}
}
if(isTM == true)
return true;
else
return false;
}
//alert("evoColor: " + localStorage.getItem('evoColor') + ". prevoColor: " + localStorage.getItem('prevoColor'))
}//end main()
// load jQuery and execute the main function
addJQuery(main);
This is the userscript I'm trying to implement this for. If anyone has any suggestions or ideas about why I'm getting the error, I'd love to hear them!

This does not work because, if you look carefully at what addJQuery does, you'll realize that it injects the code of the function you pass it into a script element that gets appended to the end of the body element.
This means that you're now working in the same space as the scripts the website has, so all GM_* are not going to be available. What you can do is to move some of the code which require those functions to outside the main function, but remember that the Greasemonkey sandbox means that code running inside the main function cannot communicate with code outside it directly. You can have indirect communication, through for example watching DOM manipulation, or even unsafeWindow, but looking at your code it does not appear to be easily separateable.

This approach will not work because addJQuery() is not transferring workspace objects to the page's scope, it's essentially recreating your code from the source.
That means that the GM_ functions are not usable because there is no link between the sandbox and the copy of the code that addJQuery() made.
If your script needs GM_ functions, then just use straight GM code with the // #require directive for things like jQuery. Your only option for Chrome is Tampermonkey.
In both cases, addJQuery()-like tricks are not needed.

Related

unable to get property 'style' of undefined or null reference for background colour

Hi I'm getting script error for below code. as I tried all the ways but no luck .
kindly help me as I'm very new to this field. atleast tell me where am I going wrong
<body onload="hightlightMoreLink(2210);hightlightMoreLink(2211);">
function hightlightMoreLink(groupID) {
var isHightlightRequired = top.document.Main.isOtherLabelingCountriesPresent(groupID)       var moreLinkColumnElement = "";
var moreLinkElement = "";
if (groupID == 2210) {
moreLinkColumnElement = document.getElementById("MoreLinkTH");        
moreLinkElement = document.getElementById("labelingMoreLink");
} else { 
moreLinkColumnElement = document.getElementById("MoreLinkTHUnblind");
moreLinkElement = document.getElementById("labelingMoreLinkUnblind");
}
if (isHightlightRequired) {
moreLinkColumnElement.style.backgroundColor = "#26339f";
moreLinkElement.style.color = "#fff";
} else {
moreLinkColumnElement.style.backgroundColor = "#f5f5f5";
(getting error on this line)
moreLinkElement.style.color = "#26339f";
}
}
Here it is working...
function hightlightMoreLink(groupID) {
var isHightlightRequired = 1
var moreLinkColumnElement="";
var moreLinkElement="";
if (groupID==2210) {
moreLinkColumnElement = document.getElementById("MoreLinkTH");
moreLinkElement = document.getElementById("labelingMoreLink");
} else {
moreLinkColumnElement = document.getElementById("MoreLinkTHUnblind");
moreLinkElement = document.getElementById("labelingMoreLinkUnblind");
}
if (isHightlightRequired) {
moreLinkColumnElement.style.backgroundColor = "#26339f";
moreLinkElement.style.color="#fff";
} else {
moreLinkColumnElement.style.backgroundColor = "#f5f5f5";
moreLinkElement.style.color="#26339f";
}
}
hightlightMoreLink(2210)
First of all, you should create a fiddle so people can better understand the problem.
Checking your code though, I think the problem is in this line:
var isHightlightRequired = top.document.Main.isOtherLabelingCountriesPresent(groupID)
Check if it is return a boolean.
Aside from that, I think you should work with classes to manipulate the elements' styles. The onload you're putting on the body is not a good practice either. Jquery has a function for that purpose.
$( document ).ready(){
hightlightMoreLink(2210);
}
Another thing I would point out is the fact that you could use jquery to manipulate the elements. As is:
$("#MoreLinkTH").css("background-color", "#26339f");
$("#labelingMoreLink").css("color", "#fff");

Force line to execute before closure

I have the following code
(function() {
var weather = new Weather();
var input = document.getElementById("inputCity");
var weatherHolder = document.getElementsByClassName("weather");
var loading = document.getElementById("loadingSign");
input.focus();
input.onkeyup = function(e) {
if (e.keyCode == 13 && input.value != "") {
loading.classList.remove("hidden");
weather.getWeather(input.value, function (returnValue) {
for (iter in returnValue) {
weatherHolder[iter].classList.remove('hidden');
document.getElementById("weather" + (parseInt(iter) + 1)).innerHTML = returnValue[iter].date;
}
});
loading.classList.add("hidden");
}
};
})();
I want to force the execution of the line loading.classList.remove("hidden"); before waiting for the closure bellow to complete.
If I remove the closure lines the script works perfectly, however, I can't make it work if the closure fails.
For instance, the code below works perfectly:
(function() {
var weather = new Weather();
var input = document.getElementById("inputCity");
var weatherHolder = document.getElementsByClassName("weather");
var loading = document.getElementById("loadingSign");
input.focus();
input.onkeyup = function(e) {
if (e.keyCode == 13 && input.value != "") {
loading.classList.remove("hidden");
alert("teste");
loading.classList.add("hidden");
}
};
})();
The problem is in the line loading.classList.remove("hidden"); . This is supposed to remove a class that's hiding a message and a spinner. If I replace the closure lines with an alert the spinner shows, however, if I have that closure function the spinner is never shown.
How can I force that line to be called whether the closure is successful or not?
I don't really understand the question but judging from the code you have, it would be wiser to add the loading.classList.add("hidden"); inside the callback so it gets executed correctly.
(function() {
var weather = new Weather();
var input = document.getElementById("inputCity");
var weatherHolder = document.getElementsByClassName("weather");
var loading = document.getElementById("loadingSign");
input.focus();
input.onkeyup = function(e) {
if (e.keyCode == 13 && input.value != "") {
loading.classList.remove("hidden");
weather.getWeather(input.value, function (returnValue) {
for (iter in returnValue) {
weatherHolder[iter].classList.remove('hidden');
document.getElementById("weather" + (parseInt(iter) + 1)).innerHTML = returnValue[iter].date;
}
// Here
loading.classList.add("hidden");
});
}
};
})();
Ok so you are asking to "force the execution of..." but in fact what I suspect is happening here is that: the line we moved was not "waiting" on getWeather to finish.

Hide div with js, but without affecting html code

Let's say we have a div with id = '123'
Ho to make it invisible with js without affecting its html code?
So document.getElementById('123').style.display = 'none' is not an option.
JS only
UPD:
I just have interesting task! I have to hide some comments with js from guestbook , but when I change html code to hide it, Server somehow understands what I've done and redirects me to warning Page. So I have to do something with that.
UPD2:
I had obfuscated script on my page
function check_divs() {
var try_again = true;
var arr_divs = document.getElementById('content').getElementsByTagName('div');
if (arr_divs.length != divs_count) {
try_again = false;
} else {
for (var i = 0; i < arr_divs.length; i++) {
if ((arr_divs[i].style.display == 'none') || (arr_divs[i].style.position == 'absolute')) {
try_again = false;
};
};
}; if (try_again) {
setTimeout(check_divs, 998);
} else {
document.location.href = '/alert.html';
};
}
This one, so my solution was to clear all timeouts.
document.getElementById('123').style.visibility = 'hidden';
or
document.getElementById('123').setAttribute('style','display:none');
or
document.getElementById('123').setAttribute('style','visibility:hidden');
or if you have jQuery libraries
$('#123').css('visibility','hidden')
or
$('#123').css('display','none')
Any of that help?

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.

AsyncFileUpload has logic error in AjaxControlToolkit, when component in a different tab, so not displayed

I am using the Nov version of the AjaxControlToolkit, and I found a logic error, but I am trying to figure out the best way to fix this, by Saturday, so that the program will work on IE.
This problem only has an error on IE, it works on Firefox3.5.
I have a AsyncFileUpload component on a tab that appears to not be visible when this function runs, and so the offset width is zero.
The problem is in the file AsyncFileUpload.pre.js, in function _app_onload, and this line:
this._innerTB.style.width = (this._inputFile.offsetWidth - 107) + "px";
I don't want to compile it from the source, but this may end up being my best option, so I can fix the error.
But, this is probably going to be my fix:
this._innerTB.style.width = ((this._inputFile.offsetWidth == 0) ? 200 : this._inputFile.offsetWidth) - 107) + "px";
But, I don't know if there is a better solution.
I could just write a new prototype function in my javascript class and just fix the logic error, which is better than recompiling. If I fix it in the code, then whenever I do an update I will need to keep replacing that line, until it gets fixed in the codebase.
But, I am trying to figure out if there is a way for an element to know that it has just become visible, as anytime you need to know the actual width of an element then you can't really set it up until it is displayed. I can't think of a way to know that, so what I tend to do is fix the elements on the tab the first time the tab is selected, but, for a generic library that is not a possible solution.
Location of the main question
So, before I send in a bug report about this I am curious if there is a better way to do it, rather than having it done when the page has been loaded, and assuming a minimum width that is probably wrong. <-- Question located here
I am using the follow code to create the element:
<cc1:AsyncFileUpload ID="AsyncFileUpload1" runat="server"
OnClientUploadError="uploadError" OnClientUploadStarted="StartUpload"
OnClientUploadComplete="UploadComplete"
CompleteBackColor="Lime" UploaderStyle="Modern" Width="400px"
ErrorBackColor="Red" ThrobberID="Throbber"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete"
UploadingBackColor="#66CCFF" />
And if it makes any difference I am using this as the ToolkitScriptManager seemed to introduce other errors, but that may have been my error:
<ajax:AjaxScriptManager ID="scriptmanager1" runat="server" EnablePartialRendering="true" ></ajax:AjaxScriptManager>
I am not certain if LoadScriptsBeforeUI would be useful, but I believe that I want the UI done before the scripts are loaded actually.
I find it interesting that the width I set isn't actually set when the dom tree is completed.
try add this attribute to your scriptmanager
LoadScriptsBeforeUI="true"
I have download the source code and fix the codeline,but it still not working,
then I add this attr to the scriptmanager,it works !!
check this page for detail if U wanna change the source code
http://ajaxcontroltoolkit.codeplex.com/SourceControl/network/Forks/keyoke/AyncFileUploadFix/changeset/changes/30da4b8d1c6d
This is the solution that's worked for me:
Apply CssClass on ajaxToolkit:AsyncFileUpload like "imageUploaderField"
Write Css .imageUploaderField input{width:100%!important;}
Source: http://ajaxcontroltoolkit.codeplex.com/workitem/27429
This isn't the ideal solution, but it does work, hopefully someone will have a better solution, as this is something I cannot submit to fix the bug. I added this to a javascript file of mine, but it is a hack, not a good solution. I had to replace the second function because of the line I commented out.
$(document).ready(function() {
Sys.Extended.UI.AsyncFileUpload.prototype._app_onload = function(sender, e) {
this.setThrobber(false);
if (this._inputFile != null) {
if (this._onchange$delegate == null) {
this._onchange$delegate = Function.createDelegate(this, this._onchange);
$addHandlers(this._inputFile, {
change: this._onchange$delegate
});
}
if (Sys.Browser.agent == Sys.Browser.Firefox) {
this._inputFile.size = 0;
var width = this._inputFile.offsetWidth;
this._inputFile.style.width = "";
while (this._inputFile.offsetWidth < width) {
this._inputFile.size++;
}
}
if (this._innerTB != null) {
this._inputFile.blur();
var inputFile = this._inputFile;
setTimeout(function() { inputFile.blur(); }, 0);
this._innerTB.style.width = ((this._inputFile.offsetWidth == 0 ? 200 : this._inputFile.offsetWidth) - 107) + "px";
this._inputFile.parentNode.style.width = this._inputFile.offsetWidth + "px";
if (Sys.Browser.agent == Sys.Browser.InternetExplorer) {
this._onmouseup$delegate = Function.createDelegate(this, this._onmouseup);
$addHandlers(this._inputFile, {
mouseup: this._onmouseup$delegate
});
}
}
}
};
Sys.UI.DomEvent.prototype._removeHandler = function (elements, eventName, handler) {
Sys._queryAll(elements, function(element) {
var browserHandler = null;
// if ((typeof (element._events) !== 'object') || !element._events) throw Error.invalidOperation(Sys.Res.eventHandlerInvalid);
var cache = element._events[eventName];
if (!(cache instanceof Array)) throw Error.invalidOperation(Sys.Res.eventHandlerInvalid);
for (var i = 0, l = cache.length; i < l; i++) {
if (cache[i].handler === handler) {
browserHandler = cache[i].browserHandler;
break;
}
}
if (typeof (browserHandler) !== 'function') throw Error.invalidOperation(Sys.Res.eventHandlerInvalid);
if (element.removeEventListener) {
element.removeEventListener(eventName, browserHandler, false);
}
else if (element.detachEvent) {
element.detachEvent('on' + eventName, browserHandler);
}
cache.splice(i, 1);
});
}
My Solution... probably not the best but works.
_app_onload: function(sender, e) {
this.setThrobber(false);
if (this._inputFile != null) {
if (this._onchange$delegate == null) {
this._onchange$delegate = Function.createDelegate(this, this._onchange);
$addHandlers(this._inputFile, {
change: this._onchange$delegate
});
}
if (Sys.Browser.agent == Sys.Browser.Firefox) {
this._inputFile.size = 0;
var width = this._inputFile.offsetWidth;
this._inputFile.style.width = "";
while (this._inputFile.offsetWidth < width) {
this._inputFile.size++;
}
}
if (this._innerTB != null) {
this._inputFile.blur();
var inputFile = this._inputFile;
setTimeout(function() { inputFile.blur(); }, 0);
if ((this._inputFile.offsetWidth - 107) >= 1) {
this._innerTB.style.width = (this._inputFile.offsetWidth - 107) + "px";
this._inputFile.parentNode.style.width = this._inputFile.offsetWidth + "px";
}
if (Sys.Browser.agent == Sys.Browser.InternetExplorer) {
this._onmouseup$delegate = Function.createDelegate(this, this._onmouseup);
$addHandlers(this._inputFile, {
mouseup: this._onmouseup$delegate
});
}
}
}
},
have forked at http://ajaxcontroltoolkit.codeplex.com/SourceControl/network/Forks/keyoke/AyncFileUploadFix

Categories

Resources