What steps can be taken to prompt an action before a URL is loaded in a specific browser?

I am attempting to perform an action before a specific URL is loaded in the <browser> element, whether it appears in a sidebar or tab.

For instance: (in the context of the browser's main window):

// This could also be the browser within a tab
var browser = document.getElementById("sidebar"); // <xul:browser>

// Execute a function when the browser's window is prepared for loading new content but before any scripts are executed
execOnWindowPrepared(browser, function(window) {
    // Inject something, for example
    window.foo = "bar";
});

// Load a URI 
browser.loadURI("chrome://foo/content/bar.xul"); // (could also be http:)

Please note that I cannot execute my action immediately after the loadURI statement as browser.contentWindow will still reference the old window.

Maybe utilizing progress listeners could help with this, but I am unsure about which flags I should await.

Answer №1

To determine which notification method to use from nsIObserverService, consider the specific actions your script needs to perform. If you are only setting window-level variables, the content-document-global-created notification would be most suitable. However, if you require access to the <html> element for tasks like inserting elements, then the document-element-inserted notification is a better choice.

Greasemonkey utilizes the document-element-inserted method when @run-at document-start is specified in the script. More information on this can be found in the Greasemonkey source code.

Answer №2

My approach concluded with the usage of this method. It was implemented through trial and error, so there might be some issues with certain cases, although I did not encounter any problems during numerous tests.

// Function that opens a URL in a browser and triggers a specified action once the window is ready
function loadInBrowserWithCallback (aBrowser, aUrl, /* function(window) */ aCallback) {
    var loadedUrl = nsIIOService.newURI(aUrl, null, null).spec;
    var lastWindow = aBrowser.contentWindow;
    lastWindow.__thisIsPrevWin = true;
    var progressListener = { 
        onLocationChange : function(aWebProgress, aRequest, aLocation, aFlags) { 
            var window = aWebProgress.DOMWindow;
            if(!window.__thisIsPrevWin && window.location.href === loadedUrl) {
                aBrowser.removeProgressListener(this);
                aCallback(window);
            }
        },
        // Additional listener functions omitted for brevity

        QueryInterface: function(aIID) {
            if (aIID.equals(Ci.nsIWebProgressListener) ||
                aIID.equals(Ci.nsISupportsWeakReference) ||
                aIID.equals(Ci.nsISupports))
                return this;
           throw Cr.NS_NOINTERFACE;
        }
    };
    aBrowser.addProgressListener(progressListener, Ci.nsIWebProgress.NOTIFY_ALL);
    aBrowser.loadURI(aUrl);
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimal Timing for Stock Trading - Uncover the Ideal Days to Purchase and Vend Stocks

One possible solution I found was related to determining the maximum profit value. const pricesEachDay = [1,2,5,8,7,1,2,3] const mainFunction = (pricesEachDay) => { let buyPrice = pricesEachDay[0]; let bestProfit = 0; let startDay = 0; ...

What is the process for updating the h1 header with text entered into an input field?

I'm working on an assignment that requires me to change the h1 heading to reflect whatever is entered into the input field. To accomplish this, I need to create a function using getElementByID. Here's what I've done so far: <!DOCTYPE htm ...

Utilizing Javascript to load and parse data retrieved from an HTTP request

Within my application, a server with a rest interface is utilized to manage all database entries. Upon user login, the objective is to load and map all user data from database models to usable models. A key distinction between the two is that database mode ...

The amount of child elements in Three.js

After creating a three js object and adding some children to it, I changed the length of children to 0. As a result, the objects went out of screen. But will this action completely remove the objects from both the screen and memory? var balls = new THREE. ...

JQuery: Implementing automatic selection in a selectbox

Seeking assistance on how to automatically preselect a value in a select box. I am trying to have the select box automatically choose admin aid VI, but my script is not functioning correctly. Can anyone provide guidance on this issue? Here is the HTML co ...

Prevent anchor tags from modifying the current URL

In the realm of React, I am endeavoring to incorporate an anchor tag that directs users to an external website "https://www.google.com/". Within my code, there exist two instances of this very anchor tag. The initial tag functions as intended, effortless ...

What is the method for striking through a line in a table?

I developed a unique jQuery script: <script type="text/javascript"> $(document).ready(function () { $('tr.inactive').each(function (index) { var tr = $(this); tr.find('td:first').after(function ...

Having trouble with loading textures in Three.js?

I'm facing an issue while trying to apply a texture to my mesh using three.js. Instead of the expected loaded texture, I am just seeing a plain black object. I followed the examples provided in the three.js documentation ( - Example) and also tried va ...

fade out row upon successful deletion using ajax

My code includes an AJAX function to delete items by row. In my table, there is a column with the action to perform the deletion. Here is the AJAX function: //delete detail function deleteDetail(id_po_req_detail) { var tr = ...

What is the best way to assign a numeric variable to the value attribute of an HTML form input?

Is there a way to assign a numeric value to the value attribute of an HTML form input element using a variable? I understand that the value attribute automatically gets converted to a string. How can I make sure the variable is read before being converted? ...

Loading Ajax causes the content to duplicate

My website is created using Wordpress as the CMS with an index featuring a long accordion-style list of post titles. Clicking on a heading loads the content for that post via Ajax onto the index page. However, I am encountering an issue where clicking a h ...

using conditional statements in an app.get() method in express js

app.get('/api/notes/:id', (req, res, next) => { fs.readFile(dataPath, 'utf-8', (err, data) => { if (err) { throw err; } const wholeData = JSON.parse(data); const objects = wholeData.notes; const inputId ...

Display an alert box in the parent window from an Iframe using jqModal canceled action

I'm currently working on a web page that includes an iFrame. I have complete access to both the parent window and the content within the iFrame. Within the iFrame, there is a jqModal cancel box that appears when the user enters invalid input. However, ...

"Underscores in an array of primary keys serve as markers for

I want to filter a list of objects using underscore based on their primary key being included in a specific array of primary keys. list = [object{pk: 1}, object{pk: 2}, object{pk: 3}] primary_key_list = [1,2] The desired outcome is to return [object{pk: ...

Is it possible to access the caller function's name from within the callee function?

Similar Inquiry: Javascript how do you find the caller function? This morning, while experimenting with javascript/jQuery, I was looking into capturing the name of the caller function that is currently being executed. For example, in the code snippet ...

While conducting tests on a Vue single file component, Jest came across an unforeseen token

I need help with setting up unit tests for my Vue application that uses single file components. I've been trying to use Jest as mentioned in this guide, but encountered an error "Jest encountered an unexpected token" along with the details below: /so ...

Heroku deployment failed: Push rejected due to lack of a Cedar-supported application

Trying to deploy my 3D game (created with three.js) on a Heroku server has brought up an issue. After running the command "git push heroku master," I encountered the following problem: Initializing repository, done. Counting objects: 252, done. Delta com ...

Dynamic JavaScript Total Calculation

I have been struggling to update the total price for specific options. Even though the code was created by someone else and has worked fine for many users, I can't seem to make it work correctly. Any assistance would be greatly appreciated. Here is t ...

Security Measures for Parsing Arrays using eval() Function

When I receive a string of an array containing objects via an http request, I use eval() to parse it. Since I am expecting an array object after parsing, how can I secure this eval() process beyond using if (Array.isArray(parsedObj)) ... Is there a bette ...

Issue with loading the main.css file

Getting Started Managing two domains can be a challenge, especially when trying to make them appear as one seamless website. In this case, I have ownership of and . Goal My goal is to merge the content of https://mauricevandorst.com/personal-page/index ...