How to get the current tab's history in a Web Extension in Firefox? - firefox

Is there an API that makes it possible to get the current tab's history in a Web Extension in Firefox? Just like when clicking and holding on the Back button, a dropdown will appear to show the current tab's history.

No. You cannot ask for the list for a certain tab by default.
You can, however, listen for the tab events onUpdated, onCreated etc. Using the tabId which stays the same, you can keep a list of URLs in a background script (background.js) which is always running if the addon is enabled.
You would do it like this:
let arr=[]; // At the top of background.js
browser.tabs.onCreated.addListener(handleCreated); // Somewhere in background.js
function handleCreated(tab) {
let tabId = tab.id;
if(arr[tabId]==null) arr[tabId] = [];
arr[tabId].push(url);
}
function getHistoryForCurrentTab(){
function currentTabs(tabs) {
// browser.tabs.query returns an array, lets assume the first one (it's safe to assume)
let tab = tabs[0];
// tab.url requires the `tabs` permission (manifest.json)
// We will now log the tab history to the console.
for(let url of arr[tab.id]){
console.log(url);
}
}
function onError(error) {
console.log(`This should not happen: ${error}`);
}
browser.tabs.query({currentWindow: true, active: true}).then(currentTabs, onError);
}
The above code is a proof of concept. Some improvements you will need to consider: implement onClosed which resets the tab history for that id (arr[tabId] = null), implement onUpdated (will be needed for sure, same logic as in handleCreated).
Links:
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs

Related

LightSwitch Tabbed screen in Browse template

I have a screen where we have 4 tabs, each tab should be displayed as per the login priority.
Ex:Department,Role,Employee,Screen are the tabs.
Each tab is having buttons to add,edit,remove the data.
by default when i log with any user its going to the first tab, but not all the users are having the first tab as their requirement.
how can i resolve this to do it dynamically in html client application
As covered towards the end of the following LightSwitch Team blog post, you can programmatically change the tab by using the screen.showTab method:
Creating a wizard-like experience for HTML client (Andy Kung)
However, in order to use this showTab API command when your screen is loading, its use needs to be delayed until the screen has fully displayed. This can be achieved in your screen's created method by using a combination of the jQuery mobile pagechange event (as the LightSwitch HTML Client uses jQuery mobile) and a setTimeout with a zero timeout (to delay the showTab until the loading screen is rendered).
The following shows a brief example of how you can use this approach to dynamically set the initial screen tab:
myapp.BrowseScreen.created = function (screen) {
var initialTabName = localStorage.getItem("Rolename") + "Tab";
$(window).one("pagechange", function (e, data) {
setTimeout(function () {
screen.showTab(initialTabName);
});
});
};
Based on your earlier post it appears that you're using LocalStorage to track your logged in user and their role.
On this basis, the above example assumes that the user's role will be the factor dictating the tab they are shown when the screen loads (the screen is named BrowseScreen in the above example).
It also assumes that your tabs are named after each employee role (suffixed with the text 'Tab') e.g. a user who is assigned the role 'DepartmentManager' would be directed to a tab called 'DepartmentManagerTab'.
Whilst slightly more involved, if you'd prefer to avoid the pagechange and setTimeout it's possible to customise the LightSwitch library to introduce a new navigationComplete screen event. This new event is ideal for executing any operations dependent upon the screen having fully rendered (such as navigating to a different tab using the showTab function).
If you'd like to introduce this additional event, you'll need to reference the un-minified version of the LightSwitch library by making the following change in your HTML client's default.htm file (to remove the .min from the end of the library script reference):
<!--<script type="text/javascript" src="Scripts/msls-?.?.?.min.js"></script>-->
<script type="text/javascript" src="Scripts/msls-?.?.?.js"></script>
The question marks in the line above will relate to the version of LightSwitch you're using.
You'll then need to locate the section of code in your Scripts/msls-?.?.?.js file that declares the completeNavigation function and change it as follows:
function completeNavigation(targetUnit) {
msls_notify(msls_shell_NavigationComplete, { navigationUnit: targetUnit });
var screen = targetUnit.screen;
var intialNavigation = !screen.activeTab;
var selectedTab = targetUnit.__pageName;
if (screen.activeTab !== selectedTab) {
callNavigationUnitScreenFunction(targetUnit, "navigationComplete", [intialNavigation, selectedTab]);
screen.activeTab = selectedTab; // Set at the end of the process to allow the previous selection to be referenced (activeTab)
}
}
function callNavigationUnitScreenFunction(navigationUnit, functionName, additionalParameters) {
var screenObject = navigationUnit.screen;
var constructorName = "constructor";
var _ScreenType = screenObject[constructorName];
if (!!_ScreenType) {
var fn = _ScreenType[functionName];
if (!!fn) {
return fn.apply(null, [screenObject, navigationUnit].concat(additionalParameters));
}
}
}
You can then use this new event in your screens as follows:
myapp.BrowseScreen.navigationComplete = function (screen, navigationUnit, intialNavigation, selectedTab) {
if (intialNavigation) {
var initialTabName = localStorage.getItem("Rolename") + "Tab";
screen.showTab(initialTabName);
}
};
This event fires whenever a navigation event completes (including a change of tab) with the initialNavigation parameter being set to true upon the initial load of the screen and the selectedTab parameter reflecting the selected tab.
Although modification to the LightSwitch library aren't uncommon with some of the more seasoned LightSwitch developers, if you decide to go down this path you'll need to thoroughly test the change for any adverse side effects. Also, if you upgrade your version of LightSwitch, you'll need to repeat the library modification in the new version.

Firefox Extension - New Tab - How To Override Preferences?

I am new to Firefox extension, that is why I use the Add On SDK.
I want to create an extension that shows a specific site every time the user opens up a new tab. This is my code so far:
var self = require("sdk/self");
var tabs = require("sdk/tabs");
// Listen for tab openings.
tabs.on('open', function onOpen(tab) {
getActiveTab();
});
function getActiveTab(){
tabs.on('activate', function (tab) {
tab.url = "http://www.example.com";
});
}
This works. But before it loads the specified domain it loads the Firefox default newtab page. Now is there an API reference to access the newtab setting and change to example.com?
Thanks,
Gerd
It was possible to change about:newtab URL using SDK:
require('sdk/preferences/service').set('browser.newtab.url', 'http://www.stackoverflow.com');
but it becomes obsolete with FF41, as there isn't a browser.newtab.url preference any more.
If you still plan on using it, you might also consider adding this to your code:
var { when: unload } = require('sdk/system/unload');
var reason;
unload( function ( reason ) {
require('sdk/preferences/service').set('browser.newtab.url', 'about:newtab');
});
so that the preference change gets undone after add-on unload. You can also pass one of unload reasons to the function: 'uninstall', 'disable', 'shutdown', 'upgrade', or 'downgrade', or not provide reason argument at all / leave it undefined.
Since the browser.newtab.url preference has been removed, this is the new way to do this: https://github.com/sblask/firefox-open-tabs-next-to-current/blob/master/lib/helpers.js#L50 The code of the module can be found here: https://dxr.mozilla.org/mozilla-central/source/browser/modules/NewTabURL.jsm
If you also want to replace the homepage, you have to change the browser.startup.homepage preference.

How to get handle of popup window (WebdriverIO)

I am very very new to automated testing and I am currently completely stuck with the following issue:
I have a webpage open(first window)
In the same test I call a .newWindow(second window) and do some stuff in that window. The last action opens new popup window(popup window).
What I need, is to set the focus on a popup window.
According to WebdriverIO API I can use .switchTab http://webdriver.io/api/window/switchTab.html
But to be able to switch to a popup window I have to indicate handle, but I don't understand how to get the handle of a popup window :(
That s my piece of code:
//this is the part where I have already second window open
it('should open email letter', function(done) {
client
.pause(2000)
.clickAndWait('[title="Password restore"]', 4000)
.clickAndWait('[title="Restore password"]', 7000) //this is the part where popup window opens
.pause(2000)
.windowHandles(function(err,res){
console.log(res, handles)
}) // I have got three handles but i dont know how to use them now
.........
There is a lot of examples in java, but i didnt find anything that would fit mine language.
Please, excuse me my dumbness, I am really a very beginner and I will appreciate if somebody could explain that to me.
Thanks a lot in advance!
we not use getCurrentTabId to remember the handle of the currently open window?
For example:
var main, popup; //your window handles
client
.getCurrentTabId(function (err, handle) {
main = handle;
})
.newWindow('http://localhost:9001/') //you are on popup window
.getCurrentTabId(function (err, handle) {
popup = handle;
})
.switchTab(main) //you are back to main window
.switchTab(popup) //you are on popup again
.close(popup) //extra bonus!
I notice you stated "The last action opens new popup window(popup window). What I need, is to set the focus on a popup window."
I had this issue. But the new window was opened when clicking on login with facebook. This caused an issue on finding the handle for the new window because I could not use .newWindow('http://localhost:9001/'). The API keys and all sorts are added as parameters when using a social login. So one has little control
To handle this I registered each window ID as its opened.
The first background step in my feature is Given I open the url "/a.html"
In the step you can set an empty array as the variable windowID with let let windowID = []
So my step file would look like this
const url = 'http://localhost:8080'
let windowID = []
this.Given(/^I open the url "([^"]*)"$/, (path) => {
browser
.url(url + path)
console.log(`# Navigating to ${url + path}`)
expect(browser.getUrl()).toEqual(url + path)
windowID.main = browser.getTabIds()
});
During the step after clicking the Facebook button you can then check all the open window ID's and drop the one that matches windowID.main
this.When(/^I authenticate with facebook$/, function (arg1) {
// log the ID of the main window
console.log('Main Window ID' + windowID.main)
browser
.pause(2000)
.getTabIds().forEach(function (value) {
if (value === windowID.main) {
// we do not need to do anything with windowID.main as it's already set
return
}
// if the value does not match windowID.main then we know its the new facebook login window
windowID.facebook = value
})
// log both of these
console.log('Main Window ID: ' + windowID.main)
console.log('Facebook Window ID: ' + windowID.facebook)
// Do the login
browser
.switchTab(windowID.facebook)
.setValue('input[name="email"]', process.env.FACEBOOK_EMAIL)
.setValue('input[name="pass"]', process.env.FACEBOOK_PASSWORD)
.submitForm('form')
});
note that I add credentials as an environment variable. This is a good idea, you don't want to commit your personal credentials to the code base. One may think well obviously, but you may not, who knows.
You had your question answered years ago, but I found this post first when trying to find a solution so it seems a sensible place to put this addition.

DOMContentLoaded events stops getting triggered. Why?

Well, I'm developing a firefox addon that reload a given set of url automatically with some modification. Its not possible to show the whole code. So, I've just copy paste the part of the code which is giving me the error.
The DOMContentLoaded event is suppose to be triggered everything a page is loaded, and it do it properly. The problem is that, if i open a new tab, then DOMContentLoaded event is not triggered in the old tab.
//Any code here runs only for the first time u start the browser
window.addEventListener("load", function() { myExtension.init(); }, false);
var myExtension = {
init: function()
{
var appcontent = document.getElementById("appcontent");
if(appcontent)
appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true);
},
onPageLoad: function(aEvent)
{
var doc = aEvent.originalTarget; // doc is document triggered "onload" event
//execute on one the top page (not on iframes)
if ((aEvent.originalTarget.nodeName == '#document') && (aEvent.originalTarget.defaultView.location.href == gBrowser.currentURI.spec))
{setTimeout(function(){showInError(doc.location='about:home'}, 500);}
},
}
I'd like to write the problem in a simple way (sorry for my bad English)
1) i run firefox, and the tab (say tab no.1) is continuously reloaded as i want.
2) the tab no.1 page continues to load repeatedly if i leave the page uninterrupted(that's what it want)
3) if i open a new tab (say tab no. 2), the new tab (tab no. 2) begins to reload continuously as i wanted. However, the tab no. 1 stops reloading.
what i want is to to keep on reloading both tab no 1 and tab no. 2. How to do it? what is wrong is my code?
It looks like you are executing the script only on currently displayed page (active tab).
If you want to execute it on other tabs, you should attach event listeners to new tabs as you open them (and don't forget to remove them when you close the tab). You can get useful snippets for this functionality at this page:
https://developer.mozilla.org/en/XUL_School/Intercepting_Page_Loads#WebProgressListeners
Try using gBrowser instead of document.getElementById("appcontent");
gBrowser.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true);
https://developer.mozilla.org/en/Code_snippets/On_page_load#Basic_onPageLoad_for_a_browser_window

Limit a firefox extension to a specific domain

I would like to write a firefox extension. This extension is not a generic extension but work specifically for a domain where I need to highlight specific html components.
How should I do that? I just want the js loaded when the user is browsing a specific domain.
My current overaly.js is basically empty (generated by the Extension Wizard):
var myextension = {
onLoad: function() {
// initialization code
this.initialized = true;
this.strings = document.getElementById("myextension-strings");
},
onMenuItemCommand: function(e) {
var promptService = Components.classes["#mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
promptService.alert(window, this.strings.getString("helloMessageTitle"),
this.strings.getString("helloMessage"));
},
onToolbarButtonCommand: function(e) {
// just reuse the function above. you can change this, obviously!
myextension.onMenuItemCommand(e);
}
};
window.addEventListener("load", myextension.onLoad, false);
And my ff-overlay.xul is:
myextension.onFirefoxLoad = function(event) {
document.getElementById("contentAreaContextMenu")
.addEventListener("popupshowing", function (e){ myextension.showFirefoxContextMenu(e); }, false);
};
myextension.showFirefoxContextMenu = function(event) {
// show or hide the menuitem based on what the context menu is on
document.getElementById("context-myextension").hidden = gContextMenu.onImage;
};
window.addEventListener("load", myextension.onFirefoxLoad, false);
I was thinking to go neanderthal and do a check inside myextension.onFirefoxLoad to see if the currentpage is the one I want but that requires the user to click the proper item on the context menu.
I'm not totally following what you have because both of those look like JS files, not XUL files. But what you probably want to do is listen for the load event coming from the web pages that are loaded. Then, in your event loader, just look at each page that loads and see whether it's coming from the specific domain you want.
A great (though not always quite as easy as it sounds) way to find out how to do something in a Firefox addon is to find another addon that does something similar. DOM Inspector and Inspect Context are your friends! The first such addon that comes to mind in this case is WikiTrust so you could try looking at that one to see if it gives you any inspiration.

Resources