Get the contents of a particular tab (Firefox add-on development) [duplicate] - javascript

This question already has answers here:
Firefox add-on get the tab body content
(3 answers)
Closed 8 years ago.
I'm working on a Firefox add-on, and with it, I need to monitor the contents of a particular site and react to DOM changes. Currently, I'm using a combination of gBrowser.contentDocument.getElementsByClassName("class") and attaching a DOMSubteeeModified event to it. But I notice that it works only when the tab is active. When I'm away using another tab, and the DOM changes in the inactive tab, it does not work. How do I get around this? The Firefox MDN is pretty scattered (and sometimes outdated), it is very frustrating for a newbie.
Here is a simplified version of what I'm doing:
var MyExtension = {
init() : function() {
if("gBrowser" in window) {
gBrowser.addEventListener("DOMContentLoaded", function(e){this.onPageLoad(e);},false);
},
onPageLoad: function(e) {
var doc = e.originalTarget;
if((/http://xxxx.xyz/v/[0-9a-z]/).test(doc.location.href)) {
MyExtension.XXX.handler(e);
}
e.originalTarget.defaultView.addEventListener("unload", function(e){MyExtension.onUnload(e);}, false);
},
onUnload: function(e) {
if((/http://xxxx.xyz/v/[0-9a-z]/).test(e.originalTarget.location.href)) {
//remove listeners and nullify references to dom objects
}
};
MyExtension.XXX = {
handler : function(e) {
//get dom element with gBrowser.contentDocument.getElementsByClassName("class");
//bind DOMSubtreeModified listener, attach a function to handle the event
}
};
window.addEventListener("load", function(e) {
window.removeEventListener("load", load, false);
MyExtension.init();
}, false);

Here's the technique I'm following, using gBrowser.selectedBrowser as documented here
var MyExtension = {
tab : null, //<---- added this line
init() : function() {
if("gBrowser" in window) {
gBrowser.addEventListener("DOMContentLoaded", function(e){this.onPageLoad(e);},false);
},
onPageLoad: function(e) {
var doc = e.originalTarget;
if((/http://xxxx.xyz/v/[0-9a-z]/).test(doc.location.href)) {
this.tab = gBrowser.selectedBrowser; //<--- GET REFERENCE TO CURRENT TAB
MyExtension.XXX.handler(e);
}
e.originalTarget.defaultView.addEventListener("unload", function(e){MyExtension.onUnload(e);}, false);
},
onUnload: function(e) {
if((/http://xxxx.xyz/v/[0-9a-z]/).test(e.originalTarget.location.href)) {
//remove listeners and nullify references to dom objects
}
};
MyExtension.XXX = {
handler : function(e) {
//get dom element
MyExtension.tab.contentDocument.getElementsByClassName("class"); //<--- GET CONTENT DOCUMENT INSIDE DESIRED TAB
//bind DOMSubtreeModified listener, attach a function to handle the event
}
};

Related

Object doesnt support property or method "attachevent"

I'm facing the subjected issue while launching IE 11 in selenium.jar.
I googled and found some solution like IE 11 needs AttachEvent handler instead of attach event in the js file. but i dont know how to modify since i'm new to js. Can someone please let me know how to do the changes.
Code below.
IEBrowserBot.prototype.modifySeparateTestWindowToDetectPageLoads = function(windowObject) {
this.pageUnloading = false;
var self = this;
var pageUnloadDetector = function() {
self.pageUnloading = true;
};
windowObject.attachEvent("onbeforeunload", pageUnloadDetector);
BrowserBot.prototype.modifySeparateTestWindowToDetectPageLoads.call(this, windowObject);
};
IEBrowserBot.prototype._fireEventOnElement = function(eventType, element, clientX, clientY) {
var win = this.getCurrentWindow();
triggerEvent(element, 'focus', false);
var wasChecked = element.checked;
// Set a flag that records if the page will unload - this isn't always accurate, because
// <a href="javascript:alert('foo'):"> triggers the onbeforeunload event, even thought the page won't unload
var pageUnloading = false;
var pageUnloadDetector = function() {
pageUnloading = true;
};
win.attachEvent("onbeforeunload", pageUnloadDetector);
this._modifyElementTarget(element);
if (element[eventType]) {
element[eventType]();
}
else {
this.browserbot.triggerMouseEvent(element, eventType, true, clientX, clientY);
}
// If the page is going to unload - still attempt to fire any subsequent events.
// However, we can't guarantee that the page won't unload half way through, so we need to handle exceptions.
try {
win.detachEvent("onbeforeunload", pageUnloadDetector);
if (this._windowClosed(win)) {
return;
}

Javascript: addEventListener only working in setTimeout

I'm trying to set event listeners but it's only working if I set them within setTimeout.
Doesn't work:
WebApp.setController('jobs', function() {
WebApp.setView('header', 'header');
WebApp.setView('nav', 'nav');
WebApp.setView('jobs', 'main');
var jobs = document.querySelectorAll('.jobs-category');
for(let i = 0; i < jobs.length; i++)
{
console.log('events added');
jobs[i].addEventListener("dragover", function( event ) {
console.log('drag over');
event.preventDefault();
});
jobs[i].addEventListener('drop', function(event) {
event.preventDefault();
console.log('dropped');
}, false);
}
});
Does work:
WebApp.setController('jobs', function() {
WebApp.setView('header', 'header');
WebApp.setView('nav', 'nav');
WebApp.setView('jobs', 'main');
window.setTimeout(function() {
var jobs = document.querySelectorAll('.jobs-category');
for(let i = 0; i < jobs.length; i++)
{
console.log('events added');
jobs[i].addEventListener("dragover", function( event ) {
console.log('drag over');
event.preventDefault();
});
jobs[i].addEventListener('drop', function(event) {
event.preventDefault();
console.log('dropped');
}, false);
}
}, 1);
});
(only setTimout is different/additionally)
setController() saves the function and executes it if the route get requested.
setView() binds HTML5-templates to DOM:
var Template = document.querySelector('#' + Name);
var Clone = document.importNode(Template.content, true);
var CloneElement = document.createElement('div');
CloneElement.appendChild(Clone);
CloneElement = this.replacePlaceholders(CloneElement);
document.querySelector(Element).innerHTML = CloneElement.innerHTML;
Why does this only work in setTimeout? I thought javascript is synchronous.
Addition: This is a single page app, which gets already loaded after DOM is ready.
Where is your Javascript within the page?
My guess is that the HTML is not ready yet when you try to register the event, this is why it only works with setTimeout.
Try either including your javascript at the bottom of the page (after the HTML) or listening to the page loaded event. See this question for info how to do that - $(document).ready equivalent without jQuery.
Per your assumption of synchronous javascript - yes it is (mostly) but also the way that the browser renders the page is (unless using async loading of scripts). Which means that HTML that is after a javascript will not be available yet.
UPDATE - per your comment of using a single page app, you must listen to the load complete/done/successful event. Another way you could bypass it will be listening to the events on the parent element (which is always there).
Hope this helps.
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
Most likely you are loading your JS file before your html content. You can't run your Javascript functions until the DOM is ready.

Windows 8 Javascript App Event Listener Issue

So currently in my windows 8 javascript app (based on the navigation template), upon navigation to the home page on app startup (home.html) from the default.js initialization point, in home.html's corresponding home.js file, I'm creating this gesture system to handle pinch to zoom and swiping back and forth (which works correctly):
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/home/home.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
processed: function (element, options) {
MyGlobals.loadBooks();
if (!MyGlobals.localSettings.values['firstRunCompleted']) {
MyGlobals.localSettings.values['firstRunCompleted'] = true;
MyGlobals.loadXmlBooksIntoDatabase();
//MyGlobals.integrityCheck();
};
WinJS.Resources.processAll();
},
ready: function (element, options) {
var myGesture = new MSGesture();
var chapterContainer = document.getElementById("main-content-area");
myGesture.target = chapterContainer;
WinJS.Namespace.define("MyGlobals", {
myGesture: myGesture,
});
chapterContainer.addEventListener("MSGestureStart", this.gestureListener, false);
chapterContainer.addEventListener("MSGestureEnd", this.gestureListener, false);
chapterContainer.addEventListener("MSGestureChange", this.gestureListener, false);
chapterContainer.addEventListener("MSInertiaStart", this.gestureListener, false);
chapterContainer.addEventListener("MSGestureTap", this.gestureListener, false);
chapterContainer.addEventListener("MSGestureHold", this.gestureListener, false);
chapterContainer.addEventListener("pointerdown", this.gestureListener, false);
},
gestureListener: function (evt) {
console.log("in gesturelistener now");
if (evt.type == "pointerdown") {
MyGlobals.myGesture.addPointer(evt.pointerId);
return;
}
if (evt.type == "MSGestureStart") {
if (evt.translationX < -3.5) {
MyGlobals.nextChapterHandler();
};
if (evt.translationX > 3.5) {
MyGlobals.previousChapterHandler();
}
};
if (evt.type == "MSGestureChange") {
if (evt.scale < 1) {
MyGlobals.fontSizeModify("decrease");
};
if (evt.scale > 1) {
MyGlobals.fontSizeModify("increase");
}
};
},
The problem though is that when I navigate to another page using WinJS.Navigation.navigate(), when I then navigate back to home.html using WinJS.Navigation.navigate(), all of the above event listeners don't work, and seem to not be added to the chapterContainer (from inspecting the live DOM). However, all other event listeners that are in the ready: function, do work perfectly (other listeners omitted from above code). Is there something wrong that I'm doing here?
Thanks a lot!
The page being navigated to also had a div with id "main-content-area", and the event listeners were going onto the old page instead of the page being navigated back to.

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
}
});

FireFox Toolbar Prefwindow unload/acceptdialog Event to Update the toolbar

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.

Categories

Resources