FireFox Toolbar Prefwindow unload/acceptdialog Event to Update the toolbar - javascript

I'm trying to develop a firefox toolbar ;)
so my structure is
In the options.xul is an PrefWindow which i'm opening over an
<toolbarbutton oncommand="esbTb_OpenPreferences()"/>
function esbTb_OpenPreferences() {
window.openDialog("chrome://Toolbar/content/options.xul", "einstellungen", "chrome,titlebar,toolbar,centerscreen,modal", this);}
so in my preferences i can set some checkboxes which indicates what links are presented in my toolbar. So when the preferences window is Closed or the "Ok" button is hitted I want to raise an event or an function which updates via DOM my toolbar.
So this is the function which is called when the toolbar is loaded. It sets the links visibility of the toolbar.
function esbTB_LoadMenue() {
var MenuItemNews = document.getElementById("esbTb_rss_reader");
var MenuItemEservice = document.getElementById("esbTb_estv");
if (!(prefManager.getBoolPref("extensions.esbtoolbar.ShowNews"))) {
MenuItemNews.style.display = 'none';
}
if (!(prefManager.getBoolPref("extensions.esbtoolbar.ShowEservice"))) {
MenuItemEservice.style.display = 'none';
}
}
So I tried some thinks like adding an eventlistener to the dialog which doesn't work... in the way I tried...
And i also tried to hand over the window object from the root window( the toolbar) as an argument of the opendialog function changed the function to this.
function esbTB_LoadMenue(RootWindow) {
var MenuItemNews = RootWindow.getElementById("esbTb_rss_reader");
var MenuItemEservice = RootWindow.getElementById("esbTb_estv");}
And then tried to Access the elements over the handover object, but this also not changed my toolbar at runtime.
So what i'm trying to do is to change the visibile links in my toolbar during the runtime and I don't get it how I should do that...
thanks in advance
-------edit-------
var prefManager = {
prefs: null,
start: function()
{
this.prefs = Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.getBranch("extensions.esbtoolbar.");
this.prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
this.prefs.addObserver("", this, false);
},
end: function()
{
this.prefs.removeObserver("", this);
},
observe: function(subject, topic, data)
{
if (topic != "nsPref:changed")
{
return;
}
//Stuff what is done when Prefs have changed
esbTB_LoadMenue();
},
SetBoolPref: function(pref,value)
{
this.prefs.setBoolPref(pref,value);
},
GetBoolPref: function(pref)
{
this.prefs.getBoolPref(pref);
}
}
So this is my implementation.

The trick is to listen to preference changes. That way your toolbar updates whenever the prefs change -- regardless if it happened through your PrefWindow, about:config or some other mechanism.
In Toolbar.js you do the following
var esbTB_observe = function(subject, topic, data) {
if (topic != "nsPref:changed") {
return;
}
// find out which pref changed and do stuff
}
var esbTB_init = function() {
prefs =
Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.getBranch("extensions.esbtoolbar.");
prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
prefs.addObserver("", esbTB_observe, false);
}
// Init addin after window loaded
window.addEventListener("load", esbTB_init, false);
Now, when the window loads, the esbTB_init() function is called in which the observer to the pref branch "extensions.esbtoolbar." is added. Later, when a pref in the branch is changed, the esbTB_observe() function is automatically called.
In esbTB_observe() you have to read the values of your prefs and adjust the toolbar.

Related

Firefox extension, storing variable value until firefox is restarted

Building a Firefox extension and I require to save a value after an action has been performed by the user. I need this value to persist until Firefox is restarted. I`m testing with this code.
Components.utils.import("chrome://***/content/symbols.jsm");
window.addEventListener("load", function() { myExtension.init() }, false);
var myExtension = {
init: function() {
document.addEventListener("DOMContentLoaded", this.onPageLoad, false);
},
onPageLoad: function() {
if (blocked == 0) {
alert("OFF");
}
else {
alert("ON");
}
blocked = 1;
}
}
symbols.jsm
var EXPORTED_SYMBOLS = ["blocked"];
var blocked = 0;
With this code Firefox is started and "OFF" is shown because variable has not been set yet.( as intended) Navigating to a different page and even opening a new tab will show "ON" how ever as soon as a new window is opened the variable is lost and "OFF" is shown. How can I make the variable value persist until all Firefox windows are closed(restart).
I do not want to set this in a preference in about:config as this can be easily changed by the user.
You can use JavaScript code modules https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Using
Your module should export functions instead of just variables e.g.
var EXPORTED_SYMBOLS = ["getBlocked", "setBlocked"];
var blocked = 0;
function getBlocked() {
return blocked;
}
function setBlocked(value) {
blocked = value;
}
and then use the functions instead of the variable name

Backbone.Marionette extending region stops onClose() function from calling

I've created a Backbone, Marionette and Require.js application and am now trying to add smooth transitioning between regions.
To do this easily* ive decided to extend the marionette code so it works across all my pages (theres a lot of pages so doing it manually would be too much)
Im extending the marionette.region open and close function. Problem is that it now doesnt call the onClose function inside each of my views.
If I add the code directly to the marionette file it works fine. So I'm probably merging the functions incorrectly, right?
Here is my code:
extendMarrionette: function () {
_.extend(Marionette.Region.prototype, {
open : function (view) {
var that = this;
// if this is the main content and should transition
if (this.$el.attr("id") === "wrapper" && document.wrapperIsHidden === true) {
this.$el.empty().append(view.el);
$(document).trigger("WrapperContentChanged")
} else if (this.$el.attr("id") === "wrapper" && document.wrapperIsHidden === false) {
$(document).on("WrapperIsHidden:open", function () {
//swap content
that.$el.empty().append(view.el);
//tell router to transition in
$(document).trigger("WrapperContentChanged");
//remove this event listener
$(document).off("WrapperIsHidden:open", that);
});
} else {
this.$el.empty().append(view.el);
}
},
//A new function Ive added - was originally inside the close function below. Now the close function calls this function.
kill : function (that) {
var view = this.currentView;
$(document).off("WrapperIsHidden:close", that)
if (!view || view.isClosed) {
return;
}
// call 'close' or 'remove', depending on which is found
if (view.close) {
view.close();
}
else if (view.remove) {
view.remove();
}
Marionette.triggerMethod.call(that, "close", view);
delete this.currentView;
},
// Close the current view, if there is one. If there is no
// current view, it does nothing and returns immediately.
close : function () {
var view = this.currentView;
var that = this;
if (!view || view.isClosed) {
return;
}
if (this.$el.attr("id") === "wrapper" && document.wrapperIsHidden === true) {
this.kill(this);
} else if (this.$el.attr("id") === "wrapper" && document.wrapperIsHidden === false) {
//Browser bug fix - needs set time out
setTimeout(function () {
$(document).on("WrapperIsHidden:close", that.kill(that));
}, 10)
} else {
this.kill(this);
}
}
});
}
Why don't you extend the Marionette.Region? That way you can choose between using your custom Region class, or the original one if you don't need the smooth transition in all cases. (And you can always extend it again if you need some specific behavior for some specific case).
https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.region.md#region-class
var MyRegion = Marionette.Region.extend({
open: function() {
//Your open function
}
kill: function() {
//Your kill function
}
close: function() {
//Your close function
}
});
App.addRegions({
navigationRegion: MyRegion
});
Perhaps your issue is that you are not passing a function to your event listener, but instead calling the code directly in the code below.
setTimeout(function(){
$(document).on("WrapperIsHidden:close", that.kill(that));
}, 10)
It is likely that you want something like this:
setTimeout(function(){
$(document).on("WrapperIsHidden:close", function (){ that.kill(that); });
}, 10)
Another possible problem is that you are mixing up your references to this/that in your kill function. It seems like you probably want var view to either be assigned to that.view or to use this rather than that throughout the method.
Answer to your additional problems:
You should try passing the view variable from the close function directly into your kill function because the reference to currentView is already changed to the new view object when you actually want to old view object. The reason this is happening is that you are setting a timeout before executing the kill function. You can see this if you look at the show source code. It expects close, open and then currentView assignment to happen synchronously in order.

Detecting when an iframe gets or loses focus

What's the correct way of detecting when an iframe gets or loses focus (i.e. will or will not receive keyboard events)? The following is not working in Fx4:
var iframe = /* my iframe */;
iframe.addEventListener("focus", function() { /* never gets called */ }, false);
You can poll "document.activeElement" to determine if it matches the iframe. Polling isn't ideal, but it works:
function checkFocus() {
if(document.activeElement == document.getElementsByTagName("iframe")[0]) {
console.log('iframe has focus');
} else {
console.log('iframe not focused');
}
}
window.setInterval(checkFocus, 1000);
i know it's old, but i also had the same problem.
i ended up using this little pice of code:
$(document).on('focusout', function(){
setTimeout(function(){
// using the 'setTimout' to let the event pass the run loop
if (document.activeElement instanceof HTMLIFrameElement) {
// Do your logic here..
}
},0);
});
Turns out it's not really possible. I had to change the logic of my page to avoid the need of tracking if the iframe has focus.
How to check when an iframe has been clicked in or out of as well as hover-state.
Note: I would highly recommend you don't choose a polling method and go with an event driven method such as this.
Disclaimer
It is not possible to use the focus or blur events directly on an iframe but you can use them on the window to provide an event driven method of checking the document.activeElement. Thus you can accomplish what you're after.
Although we're now in 2018, my code is being implemented in GTM and tries to be cross browser compatible back to IE 11. This means there's more efficient code if you're utilizing newer ES/ECMAScript features.
Setup
I'm going to take this a few steps further to show that we can also get the iframe's src attribute as well as determine if it's being hovered.
Code
You would ideally need to put this in a document ready event, or at least encapsulate it so that the variables aren't global [maybe use an IIFE]. I did not wrap it in a document ready because it's handled by GTM. It may also depend where you place this or how you're loading it such as in the footer.
https://jsfiddle.net/9285tbsm/9/
I have noticed in the JSFiddle preview that it's already an iframe, sometimes you have to focus it first before events start to capture. Other issues can be that your browser window isn't yet focused either.
// Helpers
var iframeClickedLast;
function eventFromIframe(event) {
var el = event.target;
return el && el.tagName && el.tagName.toLowerCase() == 'iframe';
}
function getIframeSrc(event) {
var el = event.target;
return eventFromIframe(event) ? el.getAttribute('src') : '';
}
// Events
function windowBlurred(e) {
var el = document.activeElement;
if (el.tagName.toLowerCase() == 'iframe') {
console.log('Blurred: iframe CLICKED ON', 'SRC:', el.getAttribute('src'), e);
iframeClickedLast = true;
}
else {
console.log('Blurred', e);
}
}
function windowFocussed(e) {
if (iframeClickedLast) {
var el = document.activeElement;
iframeClickedLast = false;
console.log('Focussed: iframe CLICKED OFF', 'SRC:', el.getAttribute('src'), e);
}
else {
console.log('Focussed', e);
}
}
function iframeMouseOver(e) {
console.log('Mouse Over', 'SRC:', getIframeSrc(e), e);
}
function iframeMouseOut(e) {
console.log('Mouse Out', 'SRC:', getIframeSrc(e), e);
}
// Attach Events
window.addEventListener('focus', windowFocussed, true);
window.addEventListener('blur', windowBlurred, true);
var iframes = document.getElementsByTagName("iframe");
for (var i = 0; i < iframes.length; i++) {
iframes[i].addEventListener('mouseover', iframeMouseOver, true);
iframes[i].addEventListener('mouseout', iframeMouseOut, true);
}
I have solved this by using contentWindow instead of contentDocument.
The good thing about contentWindow is
it works also in case user clicks another window (another application) or another browser tab. If using activeElement, if user clicks away from the entire window to go to another application, then that logic still think the iframe is in focus, while it is not
and we don't need to poll and do a setInterval at all. This uses the normal addEventListener
let iframe = document.getElementsByTagName("iframe")[0];
// or whatever way you do to grab that iFrame, say you have an `id`, then it's even more precise
if(iframe){
iframeWindow = iframe.contentWindow;
iframeWindow.addEventListener('focus', handleIframeFocused);
iframeWindow.addEventListener('blur', handleIframeBlurred);
}
function handleIframeFocused(){
console.log('iframe focused');
// Additional logic that you need to implement here when focused
}
function handleIframeBlurred(){
console.log('iframe blurred');
// Additional logic that you need to implement here when blurred
}
This solution is working for me on both mobile and desktop:
;(function pollForIframe() {
var myIframe = document.querySelector('#my_iframe');
if (!myIframe) return setTimeout(pollForIframe, 50);
window.addEventListener('blur', function () {
if (document.activeElement == myIframe) {
console.log('myIframe clicked!');
}
});
})();
The solution is to inject a javascript event on the parent page like this :
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML =
"document.addEventListener('click', function()" +
"{ if(document.getElementById('iframe')) {" +
// What you want
"}});";
head.appendChild(script);
Here is the code to Detecting when an iframe gets or loses focus
// This code can be used to verify Iframe gets focus/loses.
function CheckFocus(){
if (document.activeElement.id == $(':focus').context.activeElement.id) {
// here do something
}
else{
//do something
}
}
A compact function that accepts callbacks you want to run when iframe gets or loses focus.
/* eslint-disable no-unused-vars */
export default function watchIframeFocus(onFocus, onBlur) {
let iframeClickedLast;
function windowBlurred(e) {
const el = document.activeElement;
if (el.tagName.toLowerCase() == 'iframe') {
iframeClickedLast = true;
onFocus();
}
}
function windowFocussed(e) {
if (iframeClickedLast) {
iframeClickedLast = false;
onBlur();
}
}
window.addEventListener('focus', windowFocussed, true);
window.addEventListener('blur', windowBlurred, true);
}
This might work
document.addEventListener('click', function(event) {
var frame= document.getElementById("yourFrameID");
var isClickInsideFrame = frame.contains(event.target);
if (!isClickInsideFrame ) {
//exec code
}
});

Chrome extension: callback function not getting called

I am developing a small extension( https://docs.google.com/leaf?id=0B5ZSnXcRXnSpMmM0NTFiNGEtMzEzZS00M2YzLWI4MzItMmVmNmM3OGE1MDRh&hl=en&authkey=CLzGpOMN ) that saves all tabs in a particular window, while closing that session.
In this, when I am trying to restore the session, I am not getting callback function getting called, though the new window is successfully opened.
The funny thing is, when in developer mode, using developer tools, the callback function gets called and restored all tabs.
Please help me.
Here is the code:
function restoreTabs( saveTabName )
{
var tabVals = window.localStorage.getItem(saveTabName);
if (tabVals == null)
return;
var callbackFunc = function (window, tabValList) {
//alert('created window');
for (var i = 0; i < tabValList.length; i++) {
var tab = eval('(' + tabValList[i] + ')');
var newTabObj = {
windowId: window.id,
index: tab.index,
url: tab.url,
selected: tab.selected,
pinned: tab.pinned
};
chrome.tabs.create(newTabObj);
}
};
var tabValList = tabVals.split('|');
chrome.windows.create(null, function (win) { callbackFunc(win, tabValList); });
}
Interesting problem. Popup is getting automatically closed when you create a new window (and as a result popup code execution is terminated), that's why it works in developer mode only because it forces the popup to stay open. You need to move restoreTabs() function to a background page, you can still easily call it from your popup:
linka.onclick = function () {
chrome.extension.getBackgroundPage().restoreTabs('saveTabs'+savetabName);
};

TinyMCE - Adding a Key Binding CNRTL-S COMMAND-S to call an AJAX save Function

I'd like to learn how to bind a CNRTL-S or COMMAND-S to call a function that I have on my page which AJAX saves the textarea content's
How can I bind those two commands? I used to use the following when it was just a textarea, but since adding TinyMCE it no longer works. Suggestions?
// Keybind the Control-Save
jQuery('#text_area_content').bind('keydown', 'ctrl+s',function (evt){
saveTextArea();
return false;
});
// Keybind the Meta-Save Mac
jQuery('#text_area_content').bind('keydown', 'meta+s',function (evt){
saveTextArea();
return false;
});
Thanks
To use a custom method for saving, i declare my saving function in the tinymce.init method
tinyMCE.init({
// General options
mode: "none",
/* some standard init params, plugins, ui, custom styles, etc */
save_onsavecallback: saveActiveEditor,
save_oncancelcallback: cancelActiveEditor
});
Then i define the function itself
function saveActiveEditor() {
var activeEditor = tinyMCE.activeEditor;
var saveUrl = "http://my.ajax.path/saveStuff";
var idEditor = activeEditor.id;
var contentEditor = activeEditor.getContent();
/* the next line is for a custom language listbox to edit different locales */
var localeEditor = activeEditor.controlManager.get('lbLanguages').selectedValue;
$.post(saveUrl ,
{ id: idEditor, content: contentEditor, locale: localeEditor },
function(results) {
if (results.Success) {
// switch back to display instead of edit
return false;
}
else {
activeEditor.windowManager.alert('Error saving data');
return false;
}
},
'json'
);
return false;
}
Don't forget to return false to override the default save action that posts back your data to the server.
edit to add: i only let the user change one tinymce instance at a time. You may want to change the locating the current instance to something else :)
edit #2: TinyMce already catches the Ctrl+s binding to process the data. Since it also cleans up html and is able to handle specific rules it's given when saving, the solution i propose is to plug your way of saving in tinyMce instead of fully overriding the Ctrl+s binding
The problem here is that the tinymce iframe does not delegate the events to the parent window. You can define custom_shortcuts in tinymce and/or use the following syntax:
// to delegate it to the parent window i use
var create_keydown_event = function(combo){
var e = { type : 'keydown' }, m = combo.split(/\+/);
for (var i=0, l=m.length; i<l; i++){
switch(m[i]){
case 'ctrl': e.metaKey = true;
case 'alt': case 'shift': e[m[i] + 'Key'] = true; break;
default : e.charCode = e.keyCode = e.which = m[i].toUpperCase().charCodeAt(0);
}
}
return e;
}
var handler = function(){
setTimeout(function(){
var e = create_keydown_event(combo);
window.parent.receiveShortCutEvent(e);
}, 1);
}
//ed.addShortcut(combo, description, handler);
ed.addShortcut('ctrl+s', 'save_shortcut', handler);
in the parent window you need a function receiveShortCutEvent which will sort out what to do with it

Categories

Resources