Closing the browser event - firefox

I'm currently developing a firefox extension and I need to know when the user closed the browser , so I can call a function. I've searched firefox addon sdk documentation and I haven't found anything. Is there a solution to my problem?

require("sdk/system/unload").when(function(reason) {
if (reason === 'shutdown') {
handleShutdown();
}
if (reason === 'disable') {
handleShutdown();
}
});

tried this?
<script type="text/javascript">
$(document).ready(function(){
window.onbeforeunload = function() {
var msg =" If you're not interested please let us know what we can do to improve."
return msg;
} });
</script>

Related

Problems with multiple dropzone instances

I try to insert two dropzones (http://www.dropzonejs.com/), but I always get "Uncaught Error: Dropzone already attached."
Here is my Code. Can anybody help me.
$(document).ready(function () {
Dropzone.autoDiscover = false;
$("#DropzoneTarget_1").dropzone({url: "...."});
$("#DropzoneTarget_2").dropzone({url: "...."});
});
Thanx and greeds
I experienced the same issue if running the same code multiple times.
Prevent this error by destroying the Dropzone object instance, so only 1 instance exists at a time.
if (myDropzone1 != undefined) {
Dropzone.forElement("#DropzoneTarget_1").destroy();
}
var myDropzone1 = $("#DropzoneTarget_1").dropzone({url: "...."});
Maybe you have 'dropzone' class on yours '#DropzoneTarget_1' and '#DropzoneTarget_2'. Remove it and your code will work.
If you need default styles just config yours dropzones with
Dropzone.options.dropzoneTarget1 = {/*option:value*/}
Dropzone.options.dropzoneTarget2 = {/*option:value*/}
Remove "dropzone" class didn´t work, but this solved my problem
$(document).ready(function () {
Dropzone.autoDiscover = false;
$(".dropzone").each(function () {
new Dropzone($(this).get(0), {url: "...."});
});
});
Thanks for your help.

How to resolve jQuery conflict

I have a few lines of jQuery codes that load external pages when the links are clicked.
$(document).ready(function() {
$(".link").click(function (e) {
e.preventDefault();
var $urlToLoad = $(this).attr('href');
$("#loadarea").load($urlToLoad, function(data){
$("#loading").fadeIn('fast').fadeOut('fast');
$("#loadarea").hide().fadeIn('slow');
return false;
});
});
});
This works fine. However, when I add this one single line of additional code, which is essential on this page, "$ is undefined" error shows up.
I've tried every single technique at http://api.jquery.com/jQuery.noConflict/ but, I can't resolve the conflict.
function goto(id, t){
$(".contentbox-wrapper").animate({"left": -($(id).position().left)}, 600);
$('#slide a').removeClass('active');
$(t).addClass('active');
}
I've tried var jq=jQuery.noConflict(); to replace $ but this doesn't solve the problem.
I guess I do not understand enough of jQuery to resolve this conflict and I would really appreciate anyone who can explain what is going on so that I can learn from this.
So all together, it looks like this:
<script>
$(document).ready(function() {
$(".link").click(function (e) {
e.preventDefault();
var $urlToLoad = $(this).attr('href');
$("#loadarea").load($urlToLoad, function(data){
$("#loading").fadeIn('fast').fadeOut('fast');
$("#loadarea").hide().fadeIn('slow');
return false;
});
});
});
function goto(id, t){
$(".contentbox-wrapper").animate({"left": -($(id).position().left)}, 600);
$('#slide a').removeClass('active');
$(t).addClass('active');
}
</script>
Then I have one inline code to fire the script.
(a class="active" href="#" onClick="goto('#kr', this); return false">test
Strange thing is, that even with the error, it fires on second click.
/////////////////////////////////////
The conflict/error was resolved by converting the inline javascript.
Thanks to Huangism below.
I would just rewrite the anchor from
<a class="active" href="#" onClick="goto('#kr', this); return false">test</a>
To
<a class="active" href="#kr">test</a>
For the jquery
$('.active').on('click', function() {
var $this = $(this);
var id = $this.attr('href');
$(".contentbox-wrapper").animate({"left": -($(id).position().left)}, 600);
$('#slide a').removeClass('active');
$this.addClass('active');
return false;
});
$(document).ready(function() {
});
Should be rewritten as:
jQuery(function($) {
});
That might help you out here.
It's probably to do with the order that you're including your js files in, make sure that jquery is the first loaded file.

Click on link to hide all other content divs

Example: (werkwijze is custom, i also have the same code with other names like -contact)
$(function() {
$('#activator-werkwijze').click(function(){
$('#overlay-werkwijze').fadeIn('fast',function(){
$('#box-werkwijze').animate({'bottom':'0px'},800);
});
});
$('#boxclose-werkwijze').click(function(){
$('#box-werkwijze').animate({'bottom':'-600px'},800,function(){
$('#overlay-werkwijze').fadeOut('fast');
});
});
});
activator shows the content, boxclose closes the content.
clicking all activators opens all content while it needs to open only one and close the others..
edit got it fixed:
This is the script which works, (the overlay is useless) jsfiddle.net/8y7Sr/126/
You need to provide more information about how you are calling the pop-up script. If you are using jquery, you can just close all and then open one
$('.className').slideDown(200);
$('#specificItem').slideUp(200);
But again, you should explain how you are doing the calls in more detail for a better answer
example, put inside function jQuery
if($('.hide').css('display')=='block'){ $('.hide').slideUp(); }else{ $('.hide').slideDown(); }
$(function() {
$('.activator').each(function(){
$(this).click(function(){
showHideAnimation(clickedObj);
});
});
}
function showHideAnimation(clickedObj)
{
$('.activator').each(function(){
if($(this).id == clickedObj.id) {
$(this).fadeIn('fast',function(){
$(this).animate({'bottom':'0px'},800);
});
} else {
$(this).animate({'bottom':'-600px'},800,function(){
$(this).fadeOut('fast');
});
}
}
}
Please try this if it doesn't work properly then replace $(this) with only this

jquery .submit live click runs more than once

I use the following code to run my form ajax requests but when i use the live selector on a button i can see the ajax response fire 1 time, then if i re-try it 2 times, 3 times, 4 times and so on...
I use .live because i also have a feature to add a post and that appears instantly so the user can remove it without refreshing the page...
Then this leads to the above problem... using .click could solve this but it's not the ideal solution i'm looking for...
jQuery.fn.postAjax = function(success_callback, show_confirm) {
this.submit(function(e) {
e.preventDefault();
if (show_confirm == true) {
if (confirm('Are you sure you want to delete this item? You can\'t undo this.')) {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
} else {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
return false;
})
return this;
};
$(document).ready(function() {
$(".delete_button").live('click', function() {
$(this).parent().postAjax(function(data) {
if (data.error == true) {
} else {
}
}, true);
});
});​
EDIT: temporary solution is to change
this.submit(function(e) {
to
this.unbind('submit').bind('submit',function(e) {
the problem is how can i protect it for real because people who know how to use Firebug or the same tool on other browsers can easily alter my Javascript code and re-create the problem
If you don't want a new click event bound every time you click the button you need to unbind the event before re-binding it or you end up with multiple bindings.
To unbind events bound with live() you can use die(). I think the syntax using die() with live() is similar to this (untested):
$(document).ready(function(){
$('.delete_button').die('click').live('click', function(){
$(this).parent().postAjax(function(data){
if (data.error == true){
}else{
}
}, true);
});
});
However, if you are using jQuery 1.7 or later use on() instead of live() as live() has been deprecated since 1.7 and has many drawbacks.
See documentation for all the details.
To use on() you can bind like this (I'm assuming the delete_button is a dynamically added element) :
$(document).ready(function(){
$(document).off('click', '.delete_button').on('click', '.delete_button', function(){
$(this).parent().postAjax(function(data){
if (data.error == true){
}else{
}
}, true);
});
});
If you are using an earlier version of jQuery you can use undelegate() or unbind() and delegate() instead. I believe the syntax would be similar to on() above.
Edit (29-Aug-2012)
the problem is how can i protect it for real because people who know
how to use Firebug or the same tool on other browsers can easily alter
my Javascript code and re-create the problem
You can some-what protect your scripts but you cannot prevent anyone from executing their own custom scripts against your site.
To at least protect your own scripts to some degree you can:
Write any script in an external js file and include a reference to that in your site
Minify your files for release
Write any script in an external js file and include a reference to that in your site
That will make your html clean and leave no trace of the scripts. A user can off course see the script reference and follow that for that you can minify the files for release.
To include a reference to a script file:
<script type="text/javascript" src="/scripts/myscript.js"></script>
<script type="text/javascript" src="/scripts/myscript.min.js"></script>
Minify your files for release
Minifying your script files will remove any redundant spacing and shorten function names to letters and so no. Similar to the minified version of JQuery. The code still works but it is meaningless. Off course, the hard-core user could follow meaningless named code and eventually figure out what you are doing. However, unless you are worth hacking into I doubt anyone would bother on the average site.
Personally I have not gone through the minification process but here are some resources:
Wikipedia - Minification (programming)
Combine, minify and compress JavaScript files to load ASP.NET pages faster
How to minify (not obfuscate) your JavaScript using PHP
Edit (01-Sep-2012)
In response to adeneo's comment regarding the use of one().
I know you already found a solution to your problem by unbinding and rebinding to the submit event.
I believe though it is worth to include a mentioning of one() in this answer for completeness as binding an event with one() only executes the event ones and then unbinds itself again.
As your click event, when triggered, re-loads and rebinds itself anyway one() as an alternative to unbinding and re-binding would make sense too.
The syntax for that would be similar to on(), keeping the dynamic element in mind.
// Syntax should be right but not tested.
$(document).ready(function() {
$(document).one('click', '.delete_button', function() {
$(this).parent().postAjax(function(data) {
if (data.error == true) {} else {}
}, true);
});
});​
Related Resources
live()
die()
on()
off()
unbind()
delegate()
undelegate()
one()
EDIT AGAIN !!!! :
jQuery.fn.postAjax = function(show_confirm, success_callback) {
this.off('submit').on('submit', function(e) { //this is the problem, binding the submit function multiple times
e.preventDefault();
if (show_confirm) {
if (confirm('Are you sure you want to delete this item? You can\'t undo this.')) {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
} else {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
});
return this;
};
$(document).ready(function() {
$(this).on('click', '.delete_button', function(e) {
$(e.target.form).postAjax(true, function(data) {
if (data.error) {
} else {
}
});
});
});​
jQuery.fn.postAjax = function(success_callback, show_confirm) {
this.bind( 'submit.confirmCallback', //give your function a namespace to avoid removing other callbacks
function(e) {
$(this).unbind('submit.confirmCallback');
e.preventDefault();
if (show_confirm === true) {
if (confirm('Are you sure you want to delete this item? You can\'t undo this.')) {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
} else {
$.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
}
return false;
})
return this;
};
$(document).ready(function() {
$(".delete_button").live('click', function() {
$(this).parent().postAjax(function(data) {
if (data.error == true) {
} else {
}
}, true);
});
});​
As for the "people could use Firebug to alter my javascript" argument, it does not hold : people can also see the request that is sent by your $.post(...), and send it twice.
You do not have control over what happens in the browser, and should protect your server side treatment, rather than hoping that "it won't show twice in the browser, so it will prevent my database from being corrupt".

Ajax Broken in Browsers works in Android

I can run this code in Android app (using PhoneGap adn jQuery Mobile) but not on desktop browsers.
It gives me a syntax error in firebug for this line =
var TicketList = eval("(" + ajax.responseText + ")");
Here is the code
// JScript source code
// ran on body load
function doJsStuff()
{
var ajax = AJAX();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
var TicketList = eval("(" + ajax.responseText + ")");
if (TicketList.ListCount > 0) {
document.getElementById("opencount").innerHTML = TicketList.ListCount +" Open Tickets";
for (Ticket in TicketList.Tickets) {
// add stuff to DOM
//AddTicketToList(TicketList.Tickets[Ticket]);
}
}
else {
document.getElementById("opencount").innerHTML = "All Tickets Reviewed";
DisplayNoresults();
}
}
}
ajax.open("GET", "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open", true);
ajax.send(null);
//document.addEventListener("deviceready", onDeviceReady, false);
//event to check for PhoneGap
//$('ul').listview('refresh');
$('#mtickets').page();
//showVars();
}
function AJAX()
{
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
}
return xmlHttp;
}
**TicketList is a variable in the JSon that comes across like this=
{"Tickets" : [{"TicketID": "1054","Category": "N/A","SubmittedUserID": "bob.thebuilder","ShortDescription": "test question QID:16668","CreationDate": "2/16/2011 12:24:19 PM","TicketStatus": "Open","LongDescription": "Something is wrong with this question I know I hve the right answer but it keeps telling me I'm wrong"},{"TicketID": "1053","Category": "Mission Support","SubmittedUserID": "dave","ShortDescription": "Make courseware revisions","CreationDate": "2/16/2011 9:34:48 AM","TicketStatus": "Open","LongDescription": "Find help tickets generated by users for possible courseware update."}], "PageCount": "6", "ListCount": "11"}
Note about PhoneGap If you are trying to include phoengap functions in a place where the code may also be executed on in a browser make sure you only add the phone gap function with on "deviceready" or your browser will not render. Example:
function onload(){
//event to check for PhoneGap
document.addEventListener("deviceready", onDeviceReady, true);
}
...
function onDeviceReady()
{
// Now PhoneGap API ready
vibrate(90); // vib to ack pg ready
$("a").click(function(event){
vibrate(30); // add 30 sec vib to all links
});
}
My immediate response would be to use jQuery's getJSON method, since you're aready using jQuery. jQuery's AJAX provides a much broader base of browser compatibility. Also, every time you use eval(), a small baby somewhere cries.
var url = "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url ,function(TicketList){
if (TicketList.ListCount > 0) {
$("#opencount").html(TicketList.ListCount +" Open Tickets");
for (Ticket in TicketList.Tickets) {
...
}
} else {
$("#opencount").html("All Tickets Reviewed");
DisplayNoresults();
}
});
If this still doesn't work for you, ensure that the JSON being returned is valid. But please stick to this method, and don't use eval!!
SIMPLIFIED UPDATE
var url = "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url ,function(AnyNameYouWant){
alert(AnyNameYouWant.ListCount + " Open Tickets");
});
UPDATE USING 'DATA'
If your url becomes too long, you might begin to encounter problems. It is suggested to pass the url data via the data argument.
var url = "http://website.com/ListTicketsRequest.ashx";
var data = "PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url, data, function(AnyNameYouWant){
alert(AnyNameYouWant.ListCount + " Open Tickets");
});
Looking at your code, it seems likely to me that the syntax error isn't in the code you posted, but instead is contained in the JSON object you're evaluating in ajax.responseText. Take a look at the data being returned by the AJAX request. Is it valid Javascript? Does the page you're calling return something different to desktop browsers vs mobile? Is there an error message where the JSON code should be?
Another possibility: Is your app running on website.com? If not, Firefox is probably blocking the XMLHttpRequest from functioning properly. Firefox 3 and below block cross-site AJAX requests. Firefox 3.5 seems to allow some exceptions.

Resources