Infinite loop when redirecting to a different port on same domain

I am creating an add-on to redirect all URLs of a particular domain to a different port on the same domain. For example, redirect example.com/* to example.com:8080/*

This is the code I wrote in background.js:

function redirect(request) {
return {redirectUrl : request.url.replace(/example.com//, “example.com:8080/”)};
}

browser.webRequest.onBeforeRequest.addListener(redirect, {urls : ["://.example.com/*"]}, [“blocking”]);

Now the problem is that redirectUrl is again matched by the pattern specified in the addListener call, so it creates an infinite loop. Apparently, port numbers are disregarded in the pattern matching.

Is this a bug in Firefox, or is there any other way to do what I want?

Two asterisks in the pattern in my original post somehow got “eaten up”. There is an asterisk at the beginning of the pattern and one just after the “//”.

To get code “verbatim” text, you have to enclose it in backticks (```), otherwise words enclosed in asterisks bake the text between them italic.

function redirect(request) {
    const url = new URL(request.url);
    if (+url.port === 8080) { return; }
    url.port = 8080;
    return { redirectUrl: url.href, };
}

browser.webRequest.onBeforeRequest.addListener(redirect, {urls : ["://.example.com/*"]}, ["blocking"]);

Ah, so you can return a null object from the callback function to indicate that the request should continue unmodified. Makes perfect sense and seems pretty obvious now but I feel like an idiot for not realizing this myself!

I am using a slightly different but functionally equivalent solution though: I check whether request.url.replace(…) == request.url or not and return based on that.

While this solution works, I think it is still a workaround. Ideally, the match patterns in the addListener function should themselves allow distinguishing of port numbers.

Ideally, the match patterns […] should themselves allow distinguishing of port numbers.

Indeed. Interestingly enough neither Mozillas nor Googles documentation even mention port numbers.
Both talk about matching “hosts”, but apparently completely ignore the port …