Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a newly-opened tab's window object? [in a firefox extension]

I'm attempting to convert a Greasemonky script to an extension for Firefox and I'm trying to make my extension automatically attach a simple script to any webpage when a new tab is opened. I'm converting the script from Greasemonkey because I'd like to take advantage of advanced preferences and menu options.

I access the tab using this:

var container = gBrowser.tabContainer;
container.addEventListener("TabOpen", tabAdded, false);

function tabAdded(event) {
var newtabwindow = event.target.____ //I don't know what goes here
//attach script to newtabwindow
}

and my goal is to append the script to the document in the new tab once it loads using this function:

function scriptrunner(targetwindow) {
var myScript = targetwindow.content.document.createElement('script');
    myScript.type = 'text/javascript';
    myScript.setAttribute('src','chrome://addonname/content/addonscript.js');
    targetwindow.content.document.getElementsByTagName('head')[0].appendChild(myScript);
}

This function works fine to attach the script to the current page when attached to a toolbar button with oncommand="scriptrunner(window)", but I don't know how I could access the window in the newly opened tab, or if I should cut out the window from the equation and access the document another way.

like image 472
user2253229 Avatar asked Apr 06 '13 22:04

user2253229


People also ask

What is api tab?

Tabs let a user open several web pages in their browser window and then switch between those web pages. With the Tabs API, you can work with and manipulate these tabs to create utilities that provide users with new ways to work with tabs or to deliver the features of your extension.

How do I open a tab on the sidebar in Firefox?

Extension Metadata In order to open the sidebar click F2 button on your keyboard. If it doesn't work then open any sidebar (eg. using Ctrl+B), and change the sidebar via dropdown menu.


Video Answer


1 Answers

You are looking for contentWindow, which is a property of the browser element.

Given a tab, call gBrowser.getBrowserForTab to acquire the browser element associated with the tab. Then access either contentDocument or contentWindow property of the browser element (these are equivalent to the document and window objects you should already be familiar with).

Also -- if I'm not mistaken -- you'll need to listen for the "load" event of the contentWindow in addition to listening to events for the tab.

like image 113
jongo45 Avatar answered Sep 23 '22 15:09

jongo45