Feature: #107104 - Introduce UrlFactory JavaScript module 

See forge#107104

Description 

TYPO3 already uses the native URL and URLSearchParams objects when working with URLs. The module @typo3/core/factory/url-factory.js has been introduced to provide a consistent and convenient way to create and manage these objects.

Impact 

URL and URLSearchParams objects can now be created by the factory's createUrl() and createSearchParams() methods.

The method createUrl() creates a full URL object and automatically sets its base. It accepts the following arguments:

  • url - string
  • parameters - mixed

If provided, the parameters value is passed to createSearchParams() (described below).

The method createSearchParams() creates a URLSearchParams object and accepts the following argument:

  • parameters - mixed

Parameters can be passed as plain string values or nested objects. Passing a plain array is not supported.

Examples 

The following examples assume the existence of TYPO3.settings.ajaxUrls.my_dedicated_endpoint, pointing to the route /custom_endpoint, while being on https://localhost for documentation purposes.

Create a URL object
import { UrlFactory } from '@typo3/core/factory/url-factory.js';

const url = UrlFactory.createUrl(
    TYPO3.settings.ajaxUrls.my_dedicated_endpoint
);
console.log(url.toString());
// https://localhost/custom_endpoint
Copied!
Create a URL object containing a query string from a nested object
import { UrlFactory } from '@typo3/core/factory/url-factory.js';

const url = UrlFactory.createUrl(
    TYPO3.settings.ajaxUrls.my_dedicated_endpoint,
    {
        foo: 'bar',
        baz: {
            hello: 'world',
        },
    }
);
console.log(url.toString());
// https://localhost/custom_endpoint?foo=bar&baz[hello]=world
Copied!
Create a URLSearchParams object from a string input
import { UrlFactory } from '@typo3/core/factory/url-factory.js';

const urlSearchParams = UrlFactory.createSearchParams(
    'foo=bar&baz=bencer'
);
console.log(urlSearchParams.toString());
// foo=bar&baz=bencer
Copied!
Create a URLSearchParams object from an object input
import { UrlFactory } from '@typo3/core/factory/url-factory.js';

const urlSearchParams = UrlFactory.createSearchParams({
    foo: 'bar',
    baz: 'bencer',
});
console.log(urlSearchParams.toString());
// foo=bar&baz=bencer
Copied!