There doesn’t seem to be a way to do this. I did a bit of digging on a fresh install of Unity 202.1.1f1. Note that on different versions the behaviour might be different, but I would assume that at least for reasonably recent versions the following holds:
A forum thread here mentioned that Unity starts
<Version>EditorDataPlaybackEnginesWebGLSupportBuildToolsSimpleWebServer.exe to run the game locally. This executable accepts the port to start the server on is passed via a command line parameter, so we need to find the place where this is generated.
This happens to be in
<Version>EditorDataPlaybackEnginesWebGLSupportUnityEditor.WebGL.Extensions.dll, under which a class called
HttpServerEditorWrapper can be found via decompilation. This contains code for launching
SimpleWebServer.exe, but unfortunately, it turns out that it uses a function named
GetRandomUnusedPort(), which essentially uses the C#
TcpListener to open a temporary connection with the default port
0, which the C# documentation says the following:
In this case, the service provider will assign an available port number between 1024 and 65535.
After opening the temporary connection, the opened port is queried, temporary connection is closed, and the available port is passed as a command line parameter to
As a result, it seems that you are at the mercy of the operating system. Perhaps you could look into hosting the built project via an alternative custom method where you can configure the port yourself? Search engines know more about this, but for an example Python comes with a ready to use HTTP server that one can start in a directory to serve its contents.