Firefox addon progress listener - firefox-addon

I am using this page to implement an address bar change listener.
https://developer.mozilla.org/en-US/docs/Code_snippets/Progress_Listeners#Example.3a_Notification_when_the_value_in_Address_Bar_changes
This code does what it is supposed to do. When I navigate to a new page, it alerts the URL. However, if the URL I have is 302 or similar it causes an issue. It will alert the redirected URL and not the original URL. I need the URL before the request is sent to the server and the redirect happens. Is this possible?

I think you can check this via the onStateChange event.
var myExtension = {
oldURL: null,
init: function() {
gBrowser.addProgressListener(this);
},
uninit: function() {
gBrowser.removeProgressListener(this);
},
processNewURL: function() {},
// nsIWebProgressListener
QueryInterface: XPCOMUtils.generateQI(["nsIWebProgressListener",
"nsISupportsWeakReference"]),
onLocationChange: function(aProgress, aRequest, aURI) {
this.processNewURL(aURI);
},
onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
if (!aRequest) return;
if (aStateFlags & nsIWebProgressListener.STATE_START) {
alert(aRequest.name);
},
onProgressChange: function() {},
onStatusChange: function() {},
onSecurityChange: function() {}
};
window.addEventListener("load", function() { myExtension.init() }, false);
window.addEventListener("unload", function() { myExtension.uninit() }, false);
See more here: https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIRequest
aRequest is a nsIRequest, whose property name is the URL of the request.

Related

events not firing when creating single instance of a view, but works when mutliple instance are created

I'm a complete newbie to Backbone and am trying to get my head round few things. Im trying to build something using jQuery mobile and Backbone. Please find my code below
var WelcomePage = Backbone.View.extend({
initialize:function () {
this.template = _.template($("#welcome_template").html());
},
render:function (eventName) {
$(this.el).html(this.template());
return this;
},
events:{
"click .btn_continue" : function(){
appRouter.navigate('login',{trigger: true});
}
}
});
var Login = Backbone.View.extend({
initialize:function () {
this.template = _.template($("#login_template").html());
},
render:function (eventName) {
$(this.el).html(this.template());
return this;
},
events:{
"click .btn_login" : function(){
appRouter.navigate('dashboard',{trigger: true});
}
}
});
var Dashboard = Backbone.View.extend({
initialize:function () {
this.template = _.template($("#dashboard_template").html());
},
render:function (eventName) {
$(this.el).html(this.template());
return this;
},
events:{
"click .btn_loadImages" : function(){
console.log('load Images');
}
}
});
var Router = Backbone.Router.extend({
routes:{
"":"welcome",
"login":"login",
"dashboard":"dashboard",
},
initialize:function () {
},
welcome:function () {
this.changePage(new WelcomePage());
},
login:function () {
this.changePage(new Login());
},
dashboard:function(){
this.changePage(new Dashboard());
},
changePage:function (page) {
$(page.el).attr('data-role', 'page');
page.render();
$('body').append($(page.el));
$.mobile.changePage($(page.el), {changeHash:false, transition: 'slide'});
}
});
var appRouter = new Router();
Backbone.history.start();
Now while I go back and forth through the screens using the BACK key the events fire OK using the code above. Then I tried replacing the code for the Router with the code below
var Router = Backbone.Router.extend({
routes:{
"":"welcome",
"login":"login",
"dashboard":"dashboard",
},
initialize:function () {
},
welcome:function () {
this.changePage(v_WelcomePage);
},
login:function () {
this.changePage(v_Login);
},
dashboard:function(){
this.changePage(v_Dashboard);
},
changePage:function (page) {
$(page.el).attr('data-role', 'page');
page.render();
$('body').append($(page.el));
$.mobile.changePage($(page.el), {changeHash:false, transition: 'slide'});
}
});
var v_WelcomePage = new WelcomePage();
var v_Login = new Login();
var v_Dashboard = new Dashboard();
var appRouter = new Router();
Backbone.history.start();
I noticed when I go back to the previous screens the events stop firing. Instead of creating the instance of the view in the action of the router I have created it outside and call it each time.I hope im making some sense.
Any advice much appreciated.
Events are hooked up using jQuery when the view is instantiated, not rendered (in the Backbone View constructor function). jQuery disconnects those events when the html is removed from the page (probably in $.mobile.changePage).
So, the second time you render the page, the events will not be hooked back up. You could try calling page.delegateEvents() to manually hook up the events again, or you could re-create the view each time.

Pass a variable to JQuery UI dialog

I am deleting a record using PHP. I want to use a JQuery UI dialog to confirm the action, but I dont know how to pass a variable (my RecordID) to the redirect URL function, or allow the URL to access window.location.href.
$("#confirm" ).dialog({
resizable: false,
autoOpen: false,
modal: true,
buttons: {
'OK': function() {
window.location.href = 'url and myvar??';
$( this ).dialog( "close" );
},
'Cancel': function() {
$( this ).dialog( "close" );
}
}
});
$("#delete").click(function() {
$("#confirm").dialog( "open" ).html ( "Are U Sure?" );
return false;
});
HTML
<a href='index.php?recordid=$row[recordid]' id='delete'>DELETE</a>
Is there a good way to do this?
You can try using the .data() method to store data for you. Take a look at this answer
Passing data to a jQuery UI Dialog
For example to pass a variable, you can store it using the data function, before opening the dialog
$("#dialog_div")
.data('param_1', 'whateverdata')
.dialog("open");
Then you can get this back by:
var my_data = $("#dialog_div").data('param_1')
You want to change the configuration of the dialog on click (in this case, the behaviour of the Ok button). For that your have many solutions all of them ugly (imo). I would advice generating a dialog on the fly, and destroying it once it has been used, something like this:
$("#delete").click(function(ev) {
ev.preventDefault(); // preventDefault should suffice, no return false
var href = $(this).attr("href");
var dialog = $("<div>Are you sure?</div>");
$(dialog).dialog({
resizable: false,
autoOpen: true,
modal: true,
buttons: {
'OK': function() {
window.location = href;
$( this ).dialog( "close" );
},
'Cancel': function() {
$( this ).dialog( "close" );
}
},
close: {
$( this ).remove();
}
});
});
Or even better, encapsulate the confirm dialog into a function so that you can reuse it, like so:
function confirmDialog(msg) {
var dialog = $("<div>"+msg+"</div>");
var def = $.Deferred();
$(dialog).dialog({
resizable: false,
autoOpen: true,
modal: true,
buttons: {
'OK': function() {
def.resolve();
$( this ).dialog( "close" );
},
'Cancel': function() {
def.reject();
$( this ).dialog( "close" );
}
},
close: {
$( this ).remove();
}
});
return def.promise();
}
And then use it like so
confirmDialog("are your sure?").done(function() {
window.location = $(this).attr("href");
}).fail(function() {
// cry a little
});
You may have to check if the deferred object has been rejected or resolved before you close the dialog, to ensure the confirm rejects on close (and not just on pressing the 'Cancel' button). This can be done with a def.state() === "pending" conditional.
For more information on jquery deferred: http://api.jquery.com/category/deferred-object/
Deleting actions probably shouldn't be done using a GET, but if you wanted to do it that way I would recommend using the $.data in jQuery so each link had a data-record-id attribute. Then on click of one of the links, it pops up the dialog and when confirmed it adds that to the URL, and redirects.
Example:
$(function(){
$(".deleteLink").click(function(){
var id = $(this).data("record-id");
var myHref = $(this).attr('href');
$("#confirmDialog").dialog({
buttons:{
"Yes": function()
{
window.location.href = myHref + id;
}
}
});
});
});
<a class="deleteLink" data-record-id="1">Delete</a>
...
<div id="confirmDialog">
<p>Are you sure?</p>
</div>
HTML
<a data-title="Title" data-content="content" data-mydata="1" class="confirmation-dialog" href="#">Link</a>
JS
$('.confirmation-dialog').confirm({
buttons: {
Yes: function(){
console.log(this.$target.attr('data-mydata'));
No: function(){
}
}
});

jQuery UI autocomplete (combobox): how to fill it with the result of an AJAX request?

Is it possible to work with combobox as with usual jquery-ui ajax autocomplete field?
What I need?
I want there will be some default options and when user try to put any letters it must connect to the server to find requested information (as usual remote json autocomplete).
Is it possible at all?
Here's a heavily modified version of the jQueryUI example (gist):
$.widget("ui.combobox", {
_create: function() {
var _self = this
, options = $.extend({}, this.options, {
minLength: 0,
source: function(request, response) {
if (!request.term.length) {
response(_self.options.initialValues);
} else {
if (typeof _self.options.source === "function") {
_self.options.source(request, response);
} else if (typeof _self.options.source === "string") {
$.ajax({
url: _self.options.source,
data: request,
dataType: "json",
success: function(data, status) {
response(data);
},
error: function() {
response([]);
}
});
}
}
}
});
this.element.autocomplete(options);
this.button = $("<button type='button'> </button>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.insertAfter(this.element)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function() {
if (_self.element.autocomplete("widget").is(":visible")) {
_self.element.autocomplete("close");
return;
}
_self.element.autocomplete("search", "");
_self.element.focus();
});
}
});
Usage:
$("input_element_selector").combobox({
initialValues: ['array', 'of', 'values'],
source: /* <-- function or string performing remote search */,
/* any other valid autocomplete options */
});
Example: http://jsfiddle.net/Jpqa8/
The widget uses the supplied initialValues array as the source when the length of the search is "0" (this happens when the user clicks the dropdown button).
Supply a source parameter (function or string) that performs the remote search. You can also use any other options you would usually use with the autocomplete widget.

Remove all gmaps marker on jquery remove button

I use jquery-UI-map for gmaps, and i want to make popup when i click the maps on Gmaps.
$(function() {
$('#map_canvas').gmap( {'center': new google.maps.LatLng(-0.789275, 113.921327), 'callback': function(map) {
$(map).click( function(event) {
$('#map_canvas').gmap('addMarker', {'position': event.latLng, 'title': '', 'draggable': true, 'bound': false}, function(map, marker) {
$('#test').dialog({'modal':true, 'title': 'Edit and save point', 'buttons': {
"Remove": function() {
$(this).dialog( "close" );
$(map).setMap(null);
},
"Save": function() {
$(this).dialog( "close" );
}
}});
findLocation(marker.getPosition(), marker);
}).dragend( function(event) {
var self = this;
findLocation(event.latLng, this);
}).click( function() {
openDialog(this);
})
});
}});
I want to remove all marker when i click remove button in this code :
"Remove": function() {
$(this).dialog( "close" );
$(map).setMap(null);}
But the marker still remain, someone please help me. Thank you
in plugin version 3 one should use:
$('#map_canvas').gmap('clear', 'markers');
You should call
$('#map_canvas').gmap('clearMarkers');
Haven't worked with that plugin before but a quick glance at the API docs seems to suggest that this might work:
"Remove": function() {
$(this).dialog( "close" );
$(map).clearMarkers();
}

firefox extension button listener

In my extension where the overlay.js comprises of the following events:
var sto =
{
onLoad: function() {...},
onMenuItemCommand: function(e) {...},
onToolbarButtonCommand: function(e) {...},
};
window.addEventListener("load", function () { sto.onLoad(); }, false);
I would need a listener fired every time a button is clicked in a loaded page. How can I achieve this?
Well I'm not sure if that's what u want but u can try to do an event delegation on the entire document:
var document_mouseup_lst = EventListener.createEventListener();
doc.addEventListener("mouseup", document_mouseup_lst, false);
document_mouseup_lst.addEvent("mouseup", function click(e, callback, object){
var element = e.target;
if(element.tagName.toLowerCase() === 'button') {
if (e.which == 1) { // left click
// do whatever u want
} else if (e.which == 2) { // middle click
// do whatever u want
}
}
return false;
});
btw in order to create the eventlistener (the EventListener object which got the createEventlistener method) I used this page Ajaxian >> An alternative way to addEventListener
I found the solution - was quite easy. Ok here is the source:
https://developer.mozilla.org/en/Code_snippets/Interaction_between_privileged_and_non-privileged_pages
and the modified code:
var sto =
{
onLoad: function() {...},
onMenuItemCommand: function(e) {...},
onMouseClick: function(e) {...},
onToolbarButtonCommand: function(e) {...},
};
window.addEventListener("load", function () { sto.onLoad(); }, false);
document.addEventListener("click", function(e) { sto.onMouseClick(e); }, false, true);

Resources