Method for managing one-way passage of multiple pages in a browser
By using a global lock contention process for cross-page shared storage, the problems of excessive consumption of TCP connection resources and message asynchrony in multi-page browser environments are solved, achieving efficient and stable message push and state synchronization between multiple browser pages.
Patent Information
- Application Number
- CN202611092169.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-22
- Publication Date
- 2026-11-06
AI Technical Summary
In a multi-page browser environment, the independent establishment of a one-way push channel for services by each page leads to excessive consumption of TCP connection resources from the same origin. After the connection quota is exhausted, ordinary HTTP requests are blocked, and message reception between multiple pages is not synchronized, making it difficult to maintain state consistency.
Through a global lock contention process involving cross-page shared storage, each browser page learns about the channel occupancy status during the initialization phase. Only when there is no valid lock identifier will a single service unidirectional push channel be built. The browser also listens for changes in the global lock identifier, automatically triggers the transfer of channel control and the destruction of invalid channels, ensuring the uniqueness of the connection state and the synchronization of messages.
It resolves the resource contention issue caused by the upper limit of the number of same-origin connections in the HTTP/1.1 protocol, ensures socket resources for HTTP requests, avoids message push interruptions and data timing errors, simplifies front-end business logic, and provides a smooth multi-page interactive experience.
Smart Images

Figure CN123055697A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of real-time communication technology for web front-ends, and in particular to a method for managing unidirectional channels across multiple browser pages. Background Technology
[0002] In modern web application architectures, real-time message pushing from the server to the client has become a key capability supporting dynamic interactive experiences, widely used in scenarios such as instant notifications, status synchronization, and monitoring data refresh. To achieve this type of one-way real-time communication, developers typically employ long polling or Server-Sent Events (SSE) technologies based on the HTTP protocol. Compared to WebSocket, SSE is favored in read-only push scenarios due to its lightweight nature, native support for reconnection after disconnection, and good HTTP protocol compatibility.
[0003] However, to ensure network security and performance, web browsers impose strict limits on the number of concurrent connections for same-origin requests under the HTTP / 1.1 protocol, typically allowing only six TCP connections per domain. As web applications become increasingly complex, a complete business function often needs to load static resources, submit forms, and maintain multiple SSE (Server-Side Request) connections in parallel on the same page. When an end user opens multiple same-origin tabs in the same browser, if each tab establishes an independent SSE connection, the browser's connection quota can be exhausted very quickly. Once the connection pool is depleted, subsequent ordinary HTTP requests will be forced to suspend, leading to slow page loading, unresponsive operations, or even system crashes, severely restricting the concurrent processing capabilities of multi-page applications. Furthermore, due to the lack of cross-page connection coordination mechanisms, tabs cannot perceive each other's connection status, resulting in redundant use of server resources and making it extremely complex for clients to maintain consistent state across multiple data sources. Summary of the Invention
[0004] Based on this, the purpose of this application is to provide a browser multi-page unidirectional channel management method to solve the technical problems of excessive consumption of same-origin TCP connection resources, blocking of ordinary HTTP requests after connection quota is exhausted, and asynchronous message reception between multiple pages caused by each page independently establishing a unidirectional push service channel in the existing browser multi-tab environment.
[0005] The browser multi-page unidirectional channel management method described in this application embodiment is applied to multiple browser pages under the same domain and includes the following steps: When any browser page completes initialization and generates a unique page identifier, the following contention channel steps are executed: read the global lock identifier data stored in the cross-page shared storage and determine whether a valid lock identifier exists; if no valid lock identifier exists, write the page's unique identifier into the cross-page shared storage as a global lock identifier, and construct a single service unidirectional push channel based on the page's runtime context; if a valid lock identifier exists, do not write the page's unique identifier into the cross-page shared storage, and do not construct a single service unidirectional push channel based on the page's runtime context. When the global lock identifier of cross-page shared storage is cleared, a new page unique identifier is generated and the contention channel step is executed; when the global lock identifier of cross-page shared storage is changed and the changed global lock identifier is inconsistent with the page unique identifier of this page, the service one-way push channel built by this page based on the runtime context is destroyed.
[0006] This application's embodiments, through a global lock contention process based on cross-page shared storage, firstly utilize the step of reading global lock identifier data from the shared storage, enabling each browser page to overcome the limitations of runtime environment isolation during the initialization phase and obtain the channel occupancy status under the current domain. Based on this, only when a valid lock identifier is determined to be absent is the page's unique identifier written to the shared storage and a push channel constructed. This mechanism forces only one page within the same browser process to successfully preempt the lock resource and establish a physical connection, thereby suppressing the linear growth of SSE concurrent connections in multi-tab scenarios to a constant one, directly resolving the resource contention problem caused by the HTTP / 1.1 protocol's same-origin connection limit and ensuring the availability of socket resources for ordinary HTTP requests. Furthermore, by monitoring the step of clearing the global lock identifier in the cross-page shared storage, each browser page can automatically trigger a response process of regenerating the page identifier and re-executing the contention step when it detects that the page holding the connection has closed or crashed, causing the lock to be released. This mechanism ensures seamless transfer of channel control when a page exits abnormally, avoiding message push interruptions caused by single points of failure. Meanwhile, by monitoring for changes in the global lock identifier that are inconsistent with the identifier of the current page, the system forces pages that have lost lock control to promptly destroy the one-way push channel in their runtime context. This effectively prevents zombie connections or duplicate connection establishment due to page state desynchronization, ensuring the uniqueness and accuracy of the global connection state. Finally, since the uniqueness of the physical channel is determined by the lock identifier state in shared storage, all business messages flow in through a single active channel. Each page only needs to process the data in memory based on the lock identifier state, naturally eliminating the data timing disorder and state inconsistency problems that may occur when multiple pages receive messages independently. This significantly simplifies the synchronization logic of the front-end business code while reducing network overhead.
[0007] To better understand and implement this application, the following detailed description is provided in conjunction with the accompanying drawings. Attached Figure Description
[0008] Figure 1 This is a flowchart illustrating the browser multi-page unidirectional channel management method according to an embodiment of this application. Detailed Implementation
[0009] To make the objectives, technical solutions, and advantages of this application clearer, the embodiments of this application will be described in further detail below with reference to the accompanying drawings. Wherein, when the following description relates to the drawings, unless otherwise indicated, the same numbers in different drawings represent the same or similar elements.
[0010] It should be understood that the embodiments described below do not represent all embodiments consistent with this application. Rather, they are merely examples of apparatuses and methods consistent with some aspects of this application as detailed in the appended claims. Based on the embodiments of this application, all other embodiments obtained by those skilled in the art without inventive effort are within the scope of protection of this application.
[0011] The terminology used in this application is for the purpose of describing particular embodiments only and is not intended to be limiting of the application. The singular forms “a,” “the,” and “the” used in this application are also intended to include the plural forms unless the context clearly indicates otherwise. Furthermore, in the description of this application, unless otherwise stated, “a plurality” means two or more. It should also be understood that the term “and / or” as used herein refers to and includes any or all possible combinations of one or more associated listed items, for example, A and / or B, which can represent: A alone, A and B together, and B alone; the character “ / ” generally indicates that the preceding and following objects are in an “or” relationship.
[0012] It should be understood that although the terms first, second, third, etc., may be used in this application to describe various information, this information should not be limited to these terms, and these terms are only used to distinguish similar objects, and are not necessarily used to describe a specific order or sequence, nor should they be construed as indicating or implying relative importance. Those skilled in the art can understand the specific meaning of the above terms in this application according to the specific circumstances. Depending on the context, the word "if" as used in this application can be interpreted as "when," "when," or "in response to determination."
[0013] Please refer to Figure 1 The browser multi-page one-way channel management method described in this application embodiment is applied to multiple browser pages under the same domain name, and includes the following steps: S101: When any browser page completes initialization and generates a unique page identifier, the following contention channel steps are executed: read the global lock identifier data stored in the cross-page shared storage and determine whether a valid lock identifier exists; if no valid lock identifier exists, write the page's unique identifier into the cross-page shared storage as a global lock identifier, and construct a single service unidirectional push channel based on the page's runtime context; if a valid lock identifier exists, do not write the page's unique identifier into the cross-page shared storage, and do not construct a single service unidirectional push channel based on the page's runtime context. S102: When it is detected that the global lock identifier of cross-page shared storage has been cleared, regenerate the page unique identifier and execute the contention channel step; when it is detected that the global lock identifier of cross-page shared storage has changed and the changed global lock identifier is inconsistent with the page unique identifier of this page, destroy the service one-way push channel built by this page based on the runtime context.
[0014] This application's embodiments, through a global lock contention process based on cross-page shared storage, firstly utilize the step of reading global lock identifier data from the shared storage, enabling each browser page to overcome the limitations of runtime environment isolation during the initialization phase and obtain the channel occupancy status under the current domain. Based on this, only when a valid lock identifier is determined to be absent is the page's unique identifier written to the shared storage and a push channel constructed. This mechanism forces only one page within the same browser process to successfully preempt the lock resource and establish a physical connection, thereby suppressing the linear growth of SSE concurrent connections in multi-tab scenarios to a constant one, directly resolving the resource contention problem caused by the HTTP / 1.1 protocol's same-origin connection limit and ensuring the availability of socket resources for ordinary HTTP requests. Furthermore, by monitoring the step of clearing the global lock identifier in the cross-page shared storage, each browser page can automatically trigger a response process of regenerating the page identifier and re-executing the contention step when it detects that the page holding the connection has closed or crashed, causing the lock to be released. This mechanism ensures seamless transfer of channel control when a page exits abnormally, avoiding message push interruptions caused by single points of failure. Meanwhile, by monitoring for changes in the global lock identifier that are inconsistent with the identifier of the current page, the system forces pages that have lost lock control to promptly destroy the one-way push channel in their runtime context. This effectively prevents zombie connections or duplicate connection establishment due to page state desynchronization, ensuring the uniqueness and accuracy of the global connection state. Finally, since the uniqueness of the physical channel is determined by the lock identifier state in shared storage, all business messages flow in through a single active channel. Each page only needs to process the data in memory based on the lock identifier state, naturally eliminating the data timing disorder and state inconsistency problems that may occur when multiple pages receive messages independently. This significantly simplifies the synchronization logic of the front-end business code while reducing network overhead.
[0015] The browser multi-page one-way channel management method described in this application uses a computer device as the execution subject.
[0016] It should be noted that, in practical applications, the browser multi-page unidirectional channel management method of this embodiment can construct a unified execution script, which can be embedded in each browser page for loading and execution. That is, this embodiment provides a standardized script execution logic, enabling each browser page under the same domain to uniformly execute the script when loading, thereby autonomously completing channel management based on the same program instructions, and ultimately achieving efficient reuse and intelligent scheduling of the unidirectional push channel for services in a multi-tab environment.
[0017] Specifically, the script logic executes indiscriminately across all page execution contexts. The script's built-in competition logic prompts each page to spontaneously compete for lock tokens during the initialization phase. The winner establishes a unique SSE long-lived connection, while the loser automatically relinquishes the connection. This decentralized competition mechanism requires no server-side coordination or dedicated backend management processes; mutual exclusion access to connection resources can be achieved solely through the frontend script. Simultaneously, the embedded listening logic in the script can capture changes to shared storage across pages in real time. When the master page fails or closes, the same scripts executed on other pages immediately detect the clearing or change of lock tokens and re-initiate competition based on a pre-defined random backoff algorithm, achieving seamless transfer of channel control and self-healing from failures. Furthermore, the script's unified data encapsulation and broadcasting logic at the data level ensures that raw message data acquired by the master page can be instantly synchronized to all non-master pages via shared storage, guaranteeing consistency of state across multiple pages. Because all pages execute the same script logic, the system exhibits extremely high self-organization and symmetry. This avoids the state synchronization problems caused by code differences in traditional solutions and fundamentally eliminates the connection bottleneck under the HTTP / 1.1 protocol through a single connection strategy. Ultimately, this script logic transforms complex cross-page communication, resource contention, and state synchronization issues into a reusable automated execution process. This significantly reduces the coupling of front-end business logic, improves system stability, and greatly optimizes the utilization efficiency of browser network resources, providing users with a smooth, real-time, and seamless multi-page interactive experience.
[0018] The following provides a detailed explanation of each step.
[0019] For step S101, when any browser page completes initialization and generates a unique page identifier, the following contention channel steps are executed: read the global lock identifier data stored in the cross-page shared storage and determine whether a valid lock identifier exists; when it is determined that no valid lock identifier exists, write the unique page identifier of this page into the cross-page shared storage as a global lock identifier, and construct a single service unidirectional push channel based on the running context of this page; when it is determined that a valid lock identifier exists, do not write the unique page identifier of this page into the cross-page shared storage, and do not construct a single service unidirectional push channel based on the running context of this page.
[0020] A browser page refers to an independent instance of a web document in a browser, carried by a tab, window, or iframe. It has its own document object model (DOM) and JavaScript execution environment. In a browser's multi-process architecture, it usually corresponds to a rendering process, and there is default isolation between different browser pages.
[0021] A page unique identifier is a globally unique string or number generated by a single browser page at the beginning of its lifecycle. It is used to distinguish different page entities among multiple pages under the same origin domain. It is usually generated using a UUID algorithm combined with a hash algorithm of timestamps and strong random numbers, and is regenerated when the page is refreshed or reinitialized.
[0022] Cross-page shared storage refers to a browser-provided storage mechanism that enables data reading and writing between multiple browser pages under the same domain. Typical implementations include, but are not limited to, localStorage, IndexedDB with transactional features, and shared memory space in SharedWorker. Changes to the stored data can trigger listener events on each page, thereby breaking down the isolation of runtime environments between pages. In this embodiment, cross-page shared storage is preferably implemented using localStorage because it has inherent cross-tab read / write capabilities and storage event broadcasting capabilities.
[0023] A one-way push channel refers to a long-connection communication link established based on the HTTP protocol, in which the server continuously transmits data to the client in one direction. In the web front-end, it is specifically represented by an EventSource interface instance (i.e., SSE connection) or a fetch / XMLHttpRequest request instance that maintains a long polling state. This channel occupies the browser's TCP connection quota and is used to receive real-time messages sent by the server.
[0024] The runtime context refers to the memory space and execution environment independently occupied by a single page instance in a browser, including the JavaScript execution thread, DOM tree structure, event loop queue, and local variable scope of that page. The runtime contexts of different pages are isolated from each other and cannot directly access each other's memory data. In this embodiment, it specifically refers to the private environment of the page that carries the SSE connection instance and its callback functions.
[0025] The global lock identifier is a specific key-value record stored in the cross-page shared storage. Its value is a unique identifier of the page that currently holds the service one-way push channel permission. This identifier serves as a semaphore for cross-page mutual exclusion access and is used to arbitrate which of the multiple pages has the right to establish and maintain a physical long connection with the server.
[0026] A valid lock identifier means that the page corresponding to the global lock identifier is still active and can prove the legitimacy of its control through a heartbeat mechanism or connection keep-alive mechanism; when the page holding the lock is closed, crashed, or disconnected for more than a preset threshold, the lock identifier is considered invalid and other pages are allowed to preempt it.
[0027] In this step, a unique page identifier is generated when any browser page completes initialization. Specifically, after the browser loads any browser page from the same origin and completes DOM parsing and script execution environment preparation, the browser page first calls the browser's native `crypto.randomUUID()` interface or an algorithm that combines a timestamp with the output of a high-performance pseudo-random number generator to generate a brand new unique page identifier. This identifier serves as the browser page's unique identity credential within its current lifecycle and is used to distinguish it from other pages. Subsequently, the browser page calls the cross-page shared storage read interface to retrieve the data value with the key name `SSE_GLOBAL_LOCK`. This return value is then checked for nullability and liveness (e.g., checking if the associated heartbeat timestamp has expired) to determine if a valid lock identifier exists. If the key-value pair is not found in the cross-page shared storage or the original lock is deemed invalid based on the preset heartbeat timestamp (i.e., no valid lock identifier exists), the current browser page immediately writes its own unique page identifier into the key-value pair, completing the locking operation. Next, the page instantiates an EventSource object in its private runtime context, establishes an SSE long connection with the specified server interface, and registers event callback functions such as onmessage and onerror, thus constructing a single service unidirectional push channel and becoming the sole message receiver. If the read global lock identifier exists and is valid, it indicates that another browser page already holds control of the channel. The current page strictly adheres to the protocol, neither performing a write overwrite operation nor creating an EventSource instance locally, but only maintaining a listening state on the cross-page shared storage, thereby ensuring the uniqueness of the number of physical connections under the entire domain.
[0028] In one embodiment, the unique page identifier for each browser page in step S101 is generated through the following steps: Step S1011: Generate a random string and obtain the current timestamp; based on the random string and the current timestamp, generate a unique identifier for the page.
[0029] Random strings refer to unpredictable character sequences generated by browser pages through calling built-in cryptographically secure random number generation interfaces (such as Crypto.getRandomValues) or pseudo-random number algorithms. They are used to enhance the entropy value of identifiers and reduce the probability of collisions when multiple pages generate identifiers.
[0030] The current timestamp refers to the value representing the current time obtained by the browser page from the system clock at the moment the identifier was generated. It is usually expressed in milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC) (such as the return value of Date.now()) or a more precise time value (such as performance.now()), and is used to reflect the order in which the identifiers were generated.
[0031] Specifically, when a browser page completes initialization and prepares to generate an identifier, it first calls the browser kernel's encrypted secure random number interface (e.g., the `window.crypto.getRandomValues` method) to generate a high-strength random string. This random string consists of letters, numbers, and special symbols, and its length can be set to 16 bytes or 32 bytes depending on security requirements to ensure its unpredictability. Simultaneously, the browser page calls the system time interface to obtain the current timestamp, which is accurate to the millisecond level, reflecting the instantaneous moment of identifier generation. Subsequently, the browser page concatenates the generated random string with the obtained current timestamp to form the original combined string. To further enhance uniqueness and facilitate storage, this combined string can be hashed (e.g., using SHA-1 or MD5 algorithms), and the result is used as the final unique identifier for the page. This generation method fully utilizes the monotonicity of timestamps and the high entropy of random strings. Even if multiple browser pages concurrently perform initialization operations within the same millisecond timeframe, the differences in random strings greatly reduce the probability of identifier conflicts.
[0032] This embodiment combines timestamps and random strings to generate unique page identifiers, significantly improving the uniqueness and anti-collision capability of the identifiers in a distributed browser multi-page environment, and providing reliable basic data support for global lock contention in cross-page shared storage.
[0033] In one embodiment, step S101, which involves reading global lock identifier data stored in cross-page shared storage and determining whether a valid lock identifier exists, includes: Step S1012: If the corresponding key of the storage global lock identifier is not found in the cross-page shared storage, it is determined that there is no valid lock identifier.
[0034] The key corresponding to the global lock identifier refers to the "key" in the specific key-value pair used to store the global lock identifier in the cross-page shared storage. In this embodiment, it is usually predefined as a fixed string (such as SSE_GLOBAL_LOCK) as a unified index address when all browser pages access the global lock.
[0035] The page unique identifier format refers to the predefined regular expression rules or data structure characteristics used to verify whether the stored data is a valid page identifier. For example, it may conform to the length and character set characteristics of the UUID v4 standard, or conform to the specific encoding rules generated by the aforementioned "timestamp + random string", which is used to distinguish between valid lock identifiers and invalid dirty data.
[0036] Specifically, the browser page attempts to read data from a predefined key (e.g., SSE_GLOBAL_LOCK) by calling the getItem method of cross-page shared storage (such as localStorage). If the key does not exist in the storage system, i.e., the return value is null or undefined, it indicates that no page under that domain has attempted to establish a channel. Based on this, it is directly determined that there is no valid lock identifier, allowing the current page to proceed with the subsequent lock writing and channel construction process.
[0037] Step S1013: If the corresponding key of the storage global lock identifier is found in the cross-page shared storage, and the data in the key does not conform to the page unique identifier format, it is determined that there is no valid lock identifier.
[0038] In this step, if the corresponding key is found to exist, but the read key-value data does not conform to the preset page unique identifier format, such as a boolean value left over from an old version of the code, an empty string, a corrupted character sequence, or illegally manually modified data, then the lock identifier is determined to be invalid dirty data, and a valid lock identifier is also determined not to exist. In one embodiment, the current page can also clean up the abnormal data and overwrite the valid identifier written to itself, thereby enhancing the robustness of the solution and preventing deadlocks caused by data pollution.
[0039] Step S1014: If the corresponding key of the storage global lock identifier is found in the cross-page shared storage, and the data in the key matches the page unique identifier format, it is determined that a valid lock identifier exists.
[0040] In this step, if the corresponding key is found to exist, and the data within the key is confirmed to fully conform to the page's unique identifier format through regular expression validation or format parsing, then a valid lock identifier is determined to exist, indicating that a legitimate browser page already holds control of the channel. At this point, the current page will give up the competition, stop writing operations, and not build a one-way service push channel.
[0041] This embodiment, through the aforementioned hierarchical and progressive judgment logic, not only verifies the existence of the lock but also verifies the legality of the lock data, ensuring that the global lock identifier remains under control under any abnormal conditions (including initial loading, data corruption, or illegal writing), thus laying a solid data foundation for subsequent channel contention and management based on the global lock.
[0042] In one embodiment, step S101, which involves constructing a single service unidirectional push channel based on the runtime context of this page, includes: Step S1015: Establish an SSE long connection link between this page and the server; use the SSE long connection link as a one-way push channel for services on this page.
[0043] Among them, SSE long connection link refers to a persistent half-duplex communication link established based on the HTTP protocol and using server-sentEvents technology. This link keeps the HTTP connection open after the client initiates a request through the EventSource interface and the server responds, and continuously pushes data to the client in text / event-stream format. It has the characteristics of automatic reconnection, lightweight and native support for unidirectional data stream.
[0044] Once the browser page successfully acquires the global lock identifier during the contention channel step, it immediately performs the link establishment operation in its private runtime context. Specifically, the browser page first instantiates the EventSource interface object provided by the browser's native interface, passing the SSE-specific interface address (URL) provided by the server into the constructor, and carrying necessary authentication information (such as a token) in the request header to ensure connection security. This instantiation process establishes an SSE long-lived connection link between the page and the server. The browser's underlying layer allocates an independent TCP connection resource for this link and keeps the connection active. Subsequently, the established SSE long-lived connection link is assigned to a specific member variable in the runtime context, officially establishing it as the page's one-way service push channel. During this process, the page also registers lifecycle callback functions for this link, including but not limited to onopen (connection establishment success callback), onmessage (receiving server messages callback), and onerror (connection error callback). Because this construction action is strictly limited by the result of the global lock contention and is only executed when it is determined that no valid lock identifier exists, regardless of how many same-origin tabs exist in the browser, only this one runtime context holds an active SSE long-lived connection link at any given time.
[0045] This embodiment concretizes the abstract "one-way service push channel" into a standard SSE long connection link implementation method. It not only makes full use of the maturity and stability of the browser's native API, but also enhances the channel's survivability in complex network environments by leveraging the disconnection and reconnection mechanism built into the SSE protocol, thus ensuring the continuity of message push.
[0046] In one embodiment, after step S1015, which establishes the SSE long-lived connection link between the page and the server, the following step is also included: Step S10151: Listen for abnormal events in the SSE long connection link.
[0047] Among them, abnormal events refer to error callback signals triggered by the browser kernel or network layer during the operation of SSE long connection links. They are usually captured through the onerror callback function of the EventSource instance and cover a variety of situations that cause the link to fail to communicate normally, such as network disconnection, server-side active disconnection, cross-domain interception, connection timeout, and HTTP status code exceptions (such as 500 and 503).
[0048] Specifically, after instantiating the SSE long-connection link, the browser page holding the global lock identifier immediately binds an onerror event listener to the link's EventSource object to continuously monitor various abnormal events triggered during the link's runtime. This listening process runs within the page's runtime context and can capture underlying connection failures caused by network fluctuations, server process restarts, or gateway timeouts in real time.
[0049] Step S10152: When an abnormal interruption is detected in the SSE long connection link, the current SSE long connection link is closed, and the global lock identifier stored in the cross-page shared storage is cleared to trigger the cross-page shared storage to output change event data.
[0050] Change event data refers to an event object (usually StorageEvent) automatically generated by the browser and broadcast to all browser pages of the same origin when data in the cross-page shared storage changes. This event object contains the changed key name, old value, new value, and storage area information, and is used to notify other pages to respond to the data change in a timely manner.
[0051] When this step detects an abnormal interruption of the SSE long-lived connection (e.g., the onerror callback is triggered consecutively and the readyState property becomes CLOSED), it first calls the EventSource.close() method to actively close the currently invalid SSE long-lived connection, releasing the TCP socket resources occupied by this page and preventing half-open connections or resource leaks. Next, it calls the removeItem or setItem method of the cross-page shared storage to explicitly clear the global lock identifier stored under the corresponding key. Because data changes in cross-page shared storage (such as localStorage) have broadcast characteristics, this clearing operation will immediately trigger the browser to dispatch change event data to all pages of the same origin. This mechanism ensures that even if the main page cannot recover the connection due to network anomalies, it can actively release lock resources instead of passively waiting for the lock to expire. Other browser pages in standby mode, upon receiving the change event data, can immediately perceive the clearing or change of the global lock identifier according to the logic of step S102, thereby quickly regenerating the page's unique identifier and re-executing the contention channel steps to take over the right to establish the one-way push channel for the service. This design, which directly drives lock release based on link anomalies, fills the gap in lock cleanup that relies solely on page unload events (such as beforeunload), effectively addressing scenarios of apparent freezing caused by network layer failures.
[0052] This embodiment significantly improves the fault self-healing capability and system robustness of the service unidirectional push channel in complex network environments. Continuous monitoring ensures that the master page can detect abnormal states of SSE long-connection links in a timely manner, avoiding message loss due to silent failures. The synchronous execution of link closure and global lock flag clearing operations when an anomaly occurs effectively maps physical layer connection failures to logical layer lock resource releases. By sharing the output change event data across pages, the fault signal is broadcast instantaneously across multiple pages. This mechanism allows the system to proactively respond to network anomalies instead of simply relying on page close events or fixed heartbeat timeouts to reclaim lock resources, significantly shortening the message push window caused by network jitter or temporary server unavailability. At the same time, by promptly clearing invalid global lock flags, system deadlock caused by lock resource stagnation is prevented, ensuring that other healthy pages can quickly rebuild the service unidirectional push channel through a competition mechanism.
[0053] In one embodiment, after step S1015, which establishes the SSE long-lived connection link between the page and the server, the following step is also included: Step S10153: When the page is detected to be closed or the operation crashes, clear the global lock identifier stored in the cross-page shared storage to trigger the cross-page shared storage to output change event data.
[0054] Among them, runtime crash refers to the failure state in which the page rendering process unexpectedly exits or the script execution environment is destroyed due to abnormal reasons such as encountering uncaught JavaScript exceptions, memory overflow, main thread deadlock, or being forcibly terminated by the browser process manager. In this state, the page cannot execute cleanup logic normally, but in some browser implementations, specific lifecycle callbacks can still be triggered.
[0055] Specifically, after the browser page, acting as the controlling page, successfully establishes an SSE long connection, it registers a `window.addEventListener('beforeunload', callback)` event listener for the page's runtime context. This event is triggered when the user actively closes the tab, refreshes the page, or leaves the current page via a script, and is a standard pre-unload hook provided by the browser. When it detects that the page is about to close due to user action (such as closing a tab), it immediately calls the `removeItem` method of the cross-page shared storage in the callback function to clear the global lock identifier stored under the corresponding key. In a preferred implementation, to ensure lock release in crash scenarios, a heartbeat timeout mechanism can be used to actively perform the cleanup operation when the page is detected to be closed or crashed (specifically, when the browser can capture the process exit signal). This cleanup operation will trigger the cross-page shared storage to output change event data and broadcast it to all other browser pages of the same origin.
[0056] This embodiment complements the aforementioned abnormal interruption handling logic: abnormal interruption handling focuses on fault recovery at the network link level, while this embodiment focuses on resource release when a page entity is destroyed. This dual-protection mechanism ensures that regardless of whether the main control page loses connection due to network problems, user behavior, or system errors, the global lock identifier can be cleared in a timely manner, thereby waking up the standby page to re-initiate competition and take over the one-way service push channel.
[0057] In one embodiment, step S10152 or step S10153, which involves the browser page clearing the global lock identifier stored in the cross-page shared storage, includes: In step S10154, the browser page sends a clear command to the cross-page shared storage to trigger the cross-page shared storage to respond to the clear command, delete the global lock identifier of the storage, and output change event data to other browser pages of the same domain.
[0058] The clear command refers to an operation command issued by the browser page to the cross-page shared storage to instruct the deletion of a specific key-value pair. In the localStorage implementation, this command is specifically manifested by calling the removeItem(key) method or the setItem(key, null) method, which aims to invalidate the value of the target key or delete the key, thereby triggering the storage engine to perform the deletion action and dispatch the corresponding change notification.
[0059] Specifically, when a browser page holding the global lock detects an abnormal interruption of the SSE long-lived connection, or senses that it is about to shut down or crash, it does not directly modify the memory variable, but instead issues a clear command to the cross-page shared storage. In the implementation, this clear command is executed by calling the `localStorage.removeItem('SSE_GLOBAL_LOCK')` method in the Web Storage API; in some implementations that need to be compatible with specific browser behaviors or need to record a clear timestamp, `localStorage.setItem('SSE_GLOBAL_LOCK', '')` can also be used to set the value to null. When the cross-page shared storage engine responds to this clear command, it first deletes the global lock identifier data stored under the corresponding key, removing the key from the storage area or setting its value to null. According to browser specifications, this deletion operation will immediately trigger the storage engine to broadcast change event data (i.e., StorageEvent) to all other browser pages under the same domain. The change event data includes the key name, the old value (i.e., the unique identifier of the cleared page), and the new value (null). Other browser pages can listen for this event and instantly know that the global lock has been released without polling. This mechanism, which drives the storage engine to delete and broadcast the data by issuing a clear command, ensures that the release of the lock resource is an atomic, observable, public event, rather than a private context operation limited to the main control page. Even if the main control page crashes and subsequent scripts cannot be executed, as long as the clear command has been received and processed by the storage engine, the storage engine will still complete the deletion operation and send a notification, thereby maximizing the transmission of the lock release signal.
[0060] This embodiment significantly improves the reliability and observability of the lock release process by using a standardized operation of issuing a clear command to clear the global lock identifier. Even if the main control page crashes after issuing the clear command and cannot continue executing subsequent logic, the browser's underlying storage engine will still faithfully execute the deletion operation and dispatch change events, thereby ensuring that the lock resources will not be permanently stuck due to the unexpected exit of the main control page and preventing system deadlock.
[0061] In one embodiment, step S101, which involves destroying the one-way push channel for services built on the runtime context of this page, includes: Step S1016: Send a channel disconnect command to the current service one-way push channel to close the service one-way push channel; reclaim the network connection resources occupied by the service one-way push channel.
[0062] The channel disconnect command refers to the control signal issued by the browser page in its runtime context to an established one-way push channel instance of the service, used to actively terminate the current network communication link. In an SSE scenario based on EventSource, this command specifically manifests as calling the close() method of the EventSource object. This method notifies the browser kernel to immediately terminate the underlying TCP connection and stop receiving push data from the server.
[0063] Network connection resources refer to the underlying system resources occupied by the browser to maintain communication with the server. These mainly include TCP sockets, file descriptors, memory buffers, and the corresponding protocol stack control blocks. Under the HTTP / 1.1 protocol, these resources are strictly constrained by the upper limit of the number of concurrent connections from the same origin. Once occupied, other HTTP requests will not be able to use them until the resources are released.
[0064] When a browser page detects a change in the global lock identifier by listening for changes in cross-page shared storage and determines that the new identifier is inconsistent with the current page's identifier, it indicates that the page has lost control of the one-way push service channel, and a destruction operation must be performed. First, the currently held one-way push service channel instance (i.e., the EventSource object instance) is located within the page's runtime context, and a channel disconnect command is sent to it. In the specific implementation, this command is executed by calling the instance's `close()` method; this call immediately triggers a behavior change in the browser's underlying network stack, notifying the browser to terminate the SSE long-lived connection with the server and stop receiving any subsequent data streams pushed by the server. Following this, with the physical disconnection of the channel, the browser kernel automatically reclaims all network connection resources previously occupied by the one-way push service channel, including releasing the corresponding TCP socket, clearing the read / write buffer, and unbinding related event listeners. This process ensures that the page that has lost control does not continue to maintain an invalid "zombie connection" nor needlessly consume valuable browser connection quotas. Especially in multi-tab scenarios, if a tab fails to destroy the channel in time due to lock contention, it is very easy to cause the number of connections to accumulate and eventually reach the HTTP / 1.1 limit of 6 connections. Through the forced resource reclamation in this step, it is ensured that no matter how the channel control is transferred between different pages, the number of physical connections is always strictly controlled to one, and it is always exclusively occupied by the page that currently holds the lock, thereby maintaining the connection resources of the entire system in an optimal configuration state.
[0065] This embodiment effectively solves the resource leakage and connection deadlock problems caused by the transfer of control in a multi-page environment by introducing a destruction mechanism that sends a channel disconnect command and explicitly reclaims network connection resources. It ensures that after the global lock identifier changes, the page that loses control can quickly release its occupied same-origin connection quota, thereby avoiding the problem of connection exhaustion due to the inability to reclaim connection resources in a timely manner, and ensuring the smooth operation of other critical HTTP requests such as login and query. At the same time, by actively destroying invalid channels, it reduces the maintenance overhead of the browser's underlying network stack, reduces the invalid use of CPU and memory, and improves the overall operating efficiency of the page. Furthermore, this destruction step, together with the aforementioned lock contention and lock release steps, forms a complete closed-loop control logic: acquiring the lock establishes a connection, and changing or releasing the lock destroys the connection. This strict correspondence ensures the rigor and consistency of the service's one-way push channel in lifecycle management, providing an efficient, stable, and resource-friendly operating environment for real-time message push in multi-tab environments.
[0066] In one embodiment, after step S101, which involves constructing a single service unidirectional push channel based on the runtime context of this page, the following steps are included: Step S1017: Continuously acquire raw message data sent by the server through the one-way push channel of the service; perform unified encapsulation processing on the raw message data to generate cross-page broadcast message data.
[0067] Raw message data refers to the native data stream that the server sends directly through the SSE long connection link without being processed by the client. It usually follows the SSE protocol format (such as text lines starting with data:), contains the actual information payload required by the business, but does not contain metadata or consistency verification information required for cross-page transmission.
[0068] Unified encapsulation processing refers to the process of combining raw message data with a preset structured format. It typically includes adding information such as a unique message identifier (UUID), timestamp, message type tag, source page identifier, and checksum, transforming the loose raw data stream into a data object (such as a JSON object) with a unified structure and good extensibility, so as to facilitate standardized parsing and processing across pages.
[0069] Cross-page broadcast message data refers to standardized data packets that, after unified encapsulation and processing, can be written to cross-page shared storage and trigger change events. This data serves as a carrier, containing the core content of the original message data and its attached metadata, and is the medium connecting the holding page to synchronize information with other non-master pages.
[0070] In this step, once the browser page holding the global lock identifier successfully establishes a one-way push channel for the service, it continuously listens for the `onmessage` event of the `EventSource` instance within the page's runtime context to obtain the raw message data continuously sent by the server. Since the raw message data typically only contains the business payload and lacks the consistency identifier required for cross-page transmission, the raw message data is uniformly encapsulated: in the preferred implementation, a JSON object is constructed containing fields for `id` (unique message ID), `timestamp` (received timestamp), `type` (message type), `payload` (raw message data body), and `senderId` (unique identifier for this page). This object is then serialized to generate string-formatted cross-page broadcast message data. This encapsulation not only standardizes the data structure but also provides a basis for data deduplication and time-series verification in a multi-page environment by adding timestamps and sender identifiers.
[0071] Step S1018: Synchronize and update the cross-page broadcast message data to other browser pages of the same domain.
[0072] This step calls the `setItem` method of the cross-page shared storage to write the generated cross-page broadcast message data to a predefined broadcast key (e.g., `SSE_BROADCAST_DATA`), or overwrite the data in the auxiliary data area of the global lock identifier. Due to the characteristics of cross-page shared storage, this write operation will immediately trigger the browser to dispatch change event data to all other browser pages under the same domain. Other browser pages in standby mode, upon hearing the change event, read the cross-page broadcast message data under that broadcast key, strip the encapsulation layer to obtain the original message data, and update their own UI state or local cache. It is worth noting that to avoid performance degradation due to excessively high write frequency to cross-page shared storage, a throttle mechanism can be introduced during implementation, or large blocks of data can be temporarily stored in memory, updating the storage only when the data version number changes. Through this mechanism, service push channel data, which originally only existed in the main control page's runtime context, is efficiently broadcast to all pages of the same origin, achieving the effect of "one page receiving, multiple pages synchronizing".
[0073] This embodiment addresses the issues of data inconsistency and state fragmentation that can result from multiple pages independently receiving messages. Unified encapsulation adds necessary metadata to the raw streaming data, making messages traceable and verifiable, effectively preventing message duplication or loss due to network retransmissions or page switching. Utilizing a cross-page shared storage change broadcast mechanism, message data originally confined to the main control page's runtime context is synchronized in real-time to other browser pages, enabling all tabs to render based on the same data source and ensuring strong consistency of state across multiple pages. More importantly, this solution separates and decouples high-consumption network I / O (SSE connections) from low-consumption local I / O (storage read / write): the network layer is handled by a single page, while data distribution is accomplished using the browser kernel's efficient local broadcast capabilities. This avoids both the connection limit of HTTP / 1.1 and the server load caused by WebSocket broadcasts. Furthermore, since non-master pages can obtain real-time data without establishing a physical connection, the overall resource consumption of the system is greatly reduced, the page loading speed and response sensitivity are improved, and a seamless real-time interactive experience is provided for users when browsing multiple tabs.
[0074] In one embodiment, step S1018, which synchronizes the cross-page broadcast message data to other browser pages of the same domain, includes: Step S10181: Write the cross-page broadcast message data to the cross-page shared storage.
[0075] In this step, the browser page holding the global lock (i.e., the main control page) completes the unified encapsulation and processing of the original message data, and then calls the `setItem` method of the cross-page shared storage to write the generated cross-page broadcast message data as a string to a predefined broadcast key (e.g., the key name is `SSE_BROADCAST_PAYLOAD`). This write operation is not a simple variable assignment, but rather triggers the transaction processing flow of the browser's underlying storage engine.
[0076] Step S10182: When the cross-page shared storage detects the written cross-page broadcast message data, output a change notification event to other browser pages of the same domain.
[0077] Change notification events refer to system-level event objects (i.e., StorageEvent) automatically constructed and dispatched by the browser kernel after the cross-page shared storage detects a write or modification operation on a specific key (such as a broadcast data key). This event contains information such as the changed key name and the updated value, and is used to notify other pages of the same origin that the data has been updated. It is the core signal that drives cross-page data synchronization.
[0078] In this step, after the cross-page shared storage engine successfully executes the write operation, it immediately detects the data change of the broadcast key. Then, the browser kernel automatically constructs a change notification event (i.e., a StorageEvent instance) and broadcasts the event to all other browser pages under the same domain. (Note: According to the Web specification, the current page that triggers the write operation usually does not receive its own storage event, which just meets the requirement of this solution to only notify "other pages".)
[0079] Step S10183: When other browser pages of the same domain listen to the change notification event, read the cross-page shared storage to obtain the cross-page broadcast message data.
[0080] In this step, other browser pages under the same domain (i.e., non-master pages) capture the change notification event in real time through a pre-registered `window.addEventListener('storage', callback)` listener. In the callback function, it verifies whether the key name in the event object matches the preset broadcast key. If they match, it calls the `getItem` method of the cross-page shared storage to read the cross-page broadcast message data stored under that key. The data is then deserialized and parsed to extract the original message data for updating the page view or business logic. To address the capacity limitations and data residue issues of cross-page shared storage, in the preferred implementation, after successfully reading and processing the data, the non-master page can asynchronously call `removeItem` to clear the data for that broadcast key, or the master page can overwrite it before the next write operation to prevent storage bloat. Through this chain reaction of "write-broadcast-read," efficient data flow between multiple isolated runtime contexts is achieved.
[0081] This embodiment, through the aforementioned data synchronization mechanism based on storage change events, fully leverages the browser's native cross-page communication capabilities to achieve low-cost, high-real-time distribution of data via a one-way service push channel across multiple tabs. The change notification event, automatically triggered by the storage engine, acts as efficient system-level signaling, avoiding the performance overhead and latency of traditional polling mechanisms and ensuring instantaneous data updates. The listening and reading logic of other pages completes the data transfer from shared storage to the private runtime context. This mechanism allows non-master pages to obtain real-time data without establishing expensive SSE long connections, fundamentally solving the connection resource exhaustion problem caused by multiple pages independently establishing connections. Simultaneously, a single write source ensures the consistency and order of data received by all pages.
[0082] In one embodiment, the cross-page shared storage is a dedicated storage key in the browser's local storage that is bound to the domain name to which the browser page belongs.
[0083] Dedicated storage keys refer to specific key-value entries in cross-page shared storage (such as localStorage) that are automatically isolated based on the currently accessed domain name. Browser security mechanisms ensure the physical isolation of localStorage data under different domains, while dedicated storage keys are fixed key values defined on this basis to store specific business data (such as global lock identifiers), ensuring that all pages under the same domain access the same logical storage location.
[0084] Step S101, which involves reading the global lock identifier data stored in the cross-page shared storage, includes: Step S1019: Obtain the domain name information currently accessed by the browser page; determine the corresponding cross-page shared storage based on the domain name information; read the global lock identifier data stored in the cross-page shared storage.
[0085] Among them, domain name information refers to the hostname of the document currently loaded by the browser page. It is usually obtained through the window.location.host or document.domain property. It is the core basis for the browser to implement the Same-Origin Policy and determines which cross-page shared storage resources the page can access.
[0086] In this embodiment, the cross-page shared storage specifically uses the browser-provided localStorage object. This storage mechanism has the characteristic of being bound to a domain name, meaning that different domains have their own independent localStorage sandboxes, and all browser pages under the same domain share the same localStorage instance. This naturally meets the needs of multi-page channel management. When step S1019 is specifically executed, the browser page first calls the window.location interface in the runtime context to obtain the currently accessed domain name information (e.g., "www.example.com"). Since the access permissions of localStorage are strictly controlled by the same-origin policy, this domain name information actually defines the storage boundary that the current page can access. Subsequently, based on this domain name information, the corresponding cross-page shared storage instance (i.e., the localStorage root object under this domain) is automatically located and locked. On this basis, a unique storage key (e.g., the fixed string SSE_GLOBAL_LOCK) is generated according to preset rules, and the localStorage.getItem() method is called to read the global lock identifier data stored under this key.
[0087] This mechanism, which dynamically determines storage location based on domain name information, ensures that pages from different domains do not interfere with each other's lock states in a multi-domain deployment environment, achieving logical isolation of storage resources. For example, when a user opens two tabs, www.example.com and admin.example.com, simultaneously in a browser, although both use the same key name SSE_GLOBAL_LOCK, they are actually accessing two completely independent storage partitions due to different domain name information, thus avoiding cross-site state pollution. Through this design, the solution not only achieves connection reuse between pages of the same origin but also guarantees complete independence between pages across origins, complying with browser security design specifications.
[0088] This embodiment further enhances the standardization, security, and scalability of the solution by explicitly binding cross-page shared storage to the domain information of the browser page and using dedicated storage keys for data access. The method of dynamically locating storage instances based on domain information enables the solution to naturally support multi-domain deployment scenarios. Page groups of different business domains can independently run their own channel management mechanisms without interference, greatly enhancing the applicability of the solution.
[0089] For step S102, when it is detected that the global lock identifier of the cross-page shared storage is cleared, the page unique identifier is regenerated and the contention channel step is executed; when it is detected that the global lock identifier of the cross-page shared storage has changed and the changed global lock identifier is inconsistent with the page unique identifier of this page, the service one-way push channel built by this page based on the runtime context is destroyed.
[0090] In this step, each browser page uses the `window.addEventListener('storage', callback)` listener to continuously monitor changes in the global lock identifier in the cross-page shared storage. When the global lock identifier is cleared, for example, when the browser page holding the lock calls the `removeItem` method or when it is automatically cleared by the browser due to session termination, it indicates that the current one-way push channel for the service has been broken. At this time, each browser page will regenerate a new unique page identifier (to prevent conflicts between old identifiers under extreme contention conditions) and jump back to the contention process in step S101 to attempt to seize lock control in order to rebuild the one-way push channel for the service, thereby achieving fault self-healing and high availability. Furthermore, when each browser page detects a change in the global lock identifier and finds through string comparison that the new identifier is inconsistent with its own identifier, it indicates that the channel control has been successfully transferred to another browser page. At this time, if the browser page previously held a connection for historical reasons (e.g., briefly held it when the lock expired), it must immediately call the EventSource.close() method to destroy the one-way push channel of the service in the page's runtime context and unregister the relevant event listeners to avoid generating invalid zombie connections or wasting resources due to multi-channel concurrency.
[0091] In one embodiment, when the cross-page shared storage is cleared or changed by the global lock identifier, the corresponding change event data is output to each browser page. Step S102: When it is detected that the global lock identifier of cross-page shared storage has been cleared, regenerate the page unique identifier and execute the contention channel step; when it is detected that the global lock identifier of cross-page shared storage has changed and the changed global lock identifier is inconsistent with the page unique identifier of this page, destroy the service one-way push channel built by this page based on the runtime context, including: Step S1021: When the change event data output by the cross-page shared storage is detected, the change event data is parsed to identify the state change of the global lock identifier; when the global lock identifier is detected to be cleared, the page unique identifier is regenerated and the contention channel step is executed; when the global lock identifier is detected to have changed and the changed global lock identifier is inconsistent with the page unique identifier of this page, the service one-way push channel built by this page based on the runtime context is destroyed.
[0092] Among them, state change refers to the logical migration of the global lock identifier in the cross-page shared storage, including changing from "existing valid value" to "not existing (cleared)" or from "value A" to "value B". This change is a direct manifestation of the release or transfer of lock control and is the fundamental basis for triggering each browser page to re-evaluate its own role (master or non-master).
[0093] In this embodiment, when the cross-page shared storage (such as localStorage) detects that the global lock identifier has been cleared (e.g., the main page performs a removeItem operation) or has changed (e.g., a new page writes a new identifier via setItem), it will automatically construct and output change event data (StorageEvent). Each browser page has registered a window.addEventListener('storage', handler) listener during initialization. When the browser page detects the change event data, it first enters the event parsing stage: it reads the key attribute in the event object and verifies whether it matches the preset global lock identifier exclusive storage key (e.g., SSE_GLOBAL_LOCK). If it matches, it further parses the newValue and oldValue attributes to determine the specific state change. If the parsing finds that newValue is null or an empty string, it indicates that the global lock identifier has been cleared, which means that the original main page has released the lock resource or exited abnormally. At this time, the current page will regenerate a new page unique identifier (to avoid confusion with the old, invalid identifier) and immediately jump to the contention channel step in step S101 to try to seize lock control in order to rebuild the one-way push channel of the service. Conversely, if parsing reveals that `newValue` is not empty and differs from `oldValue`, indicating a change in the global lock identifier, an identity comparison is performed: `newValue` (the changed global lock identifier) is compared with the unique identifier held by this page. If they do not match, it confirms that this page has lost lock control (the lock has been transferred to another page). At this point, the destruction process is immediately executed, sending a channel disconnect command to the one-way push channel in the page's runtime context, calling the `close()` method to terminate the connection, and reclaiming the occupied network connection resources. This event-driven state machine transition mechanism allows all pages to perceive lock state transitions in real time and respond accurately, without relying on inefficient polling mechanisms.
[0094] This embodiment significantly improves the real-time performance and decision-making accuracy of the multi-page channel management system by introducing a status parsing and response mechanism based on change event data.
[0095] In one embodiment, when step S102 detects that the global lock identifier for cross-page shared storage has been cleared, a new page unique identifier is generated and the contention channel step is executed, including: Step S1022: When it is detected that the global lock identifier of cross-page shared storage has been cleared, wait for a random amount of time, regenerate the page unique identifier, and execute the contention channel step.
[0096] The random duration refers to an uncertain waiting time inserted by the browser page when responding to the event that the global lock flag is cleared, before executing the re-competition logic. This duration is usually generated by calling a mathematical function (such as Math.random()), and the value can be set between 0 and 500 milliseconds. The purpose is to artificially stagger the time when multiple pages perform write operations at the same time, thereby reducing the probability of concurrency conflicts.
[0097] When any browser page listens to the change event data output from the cross-page shared storage and parses and identifies that the global lock identifier has been cleared (e.g., the original controlling page is closed or crashed, triggering a clear instruction), it does not immediately execute the step of regenerating the page unique identifier and the contention channel. Instead, it first starts a waiting timer. The waiting duration set for this timer is a random duration, and its specific generation logic is as follows: calling the JavaScript Math.random() function to generate a pseudo-random number between 0 and 1, and multiplying it by a preset maximum backoff time threshold (e.g., 500 milliseconds) to obtain any integer value between 0 and 500 milliseconds. Subsequently, the current page pauses the execution of the contention logic, waits for the random duration to end, and then regenerates the page unique identifier and jumps to the contention channel step in step S101 (i.e., reading the cross-page shared storage and attempting to write a new lock identifier). The reason for this design is that in scenarios where users close multiple tabs simultaneously or the network recovers instantaneously, causing a batch of locks to be released, all surviving browser pages will almost simultaneously listen to the lock clearing change event within the same millisecond. Without a random waiting mechanism, these pages would concurrently send write requests to the cross-page shared storage. Although localStorage write operations are atomic, the high-concurrency "read-determine-write" composite operations could still lead to unnecessary resource contention, storage jitter, and even, under extreme race conditions, cause the browser's storage mechanism to be temporarily blocked due to excessively high write frequency. By introducing a random duration, the competition time points of each page are artificially staggered, making the lock acquisition process an ordered, probabilistic serial process. This significantly reduces the instantaneous pressure on the storage system, improves the success rate of lock allocation, and enhances the overall stability of the system.
[0098] This embodiment introduces a randomized waiting time mechanism to distribute high-density write requests that might otherwise be concentrated in the same time slice across a single time interval, significantly reducing the probability of concurrent conflicts during lock reconstruction in cross-page shared storage (especially localStorage). This not only avoids storage performance fluctuations or short-term browser kernel blocking caused by high-frequency concurrent writes, but also improves the atomicity and success rate of global lock identifier write operations, ensuring a smooth transition of the system during lock resource reallocation. Simultaneously, due to the introduction of randomized waiting time, the chance of each page acquiring the lock becomes statistically more equal, preventing a specific page from monopolizing lock resources for a long period due to its faster execution speed, thus enhancing the fairness of resource allocation in a multi-page environment.
[0099] In one embodiment, the method further includes the following steps: Step S103: When other browser pages of the same domain do not detect the change notification event corresponding to the global lock identifier within a preset time period, and the corresponding key of the global lock identifier can still be retrieved by querying the cross-page shared storage, it is determined that the original browser page holding the lock is invalid, a new page unique identifier is generated, and the competition channel step is executed.
[0100] The preset duration refers to the timeout threshold used to determine the liveness status of the main control page. It is usually set by the developers in advance according to the business's requirements for real-time performance (e.g., 3000 milliseconds to 10000 milliseconds). If no update or change event of the global lock identifier is detected within this time period, it is considered that the page holding the lock has lost connection.
[0101] Failure refers to an abnormal state in which a browser page holding a global lock identifier is unable to perform normal lock renewal or clearing operations due to reasons such as process freeze, machine hibernation, browser lag, or extreme operation crash, and is also unable to receive messages through the SSE link, but the lock identifier remains in the cross-page shared storage.
[0102] In this embodiment, step S103 is added as a fallback detection logic for the global lock mechanism to address potential monitoring blind spots in the event listening mechanism. Although step S102 can cover most lock release or change scenarios by listening to change notification events, in some extreme cases, such as a hard crash in the rendering process of the browser page holding the lock, or a complete pause of the JavaScript engine caused by the user putting the device to sleep, the browser may not be able to trigger the beforeunload event or issue a clear command, resulting in the global lock identifier remaining in the cross-page shared storage, forming a "zombie lock". To solve this problem, other browser pages under the same domain (including non-master pages in standby mode and newly opened pages) will periodically or at specific times (such as when the page switches from the background to the foreground) start a timer during operation. If the page does not listen to the change notification event corresponding to the global lock identifier within a preset time (e.g., 5 seconds), and actively querying the cross-page shared storage can still retrieve the corresponding key and specific value of the global lock identifier, the original browser page holding the lock is determined to be invalid. At this point, the current page no longer waits indefinitely but actively intervenes, regenerating a new unique page identifier and executing the channel contention step in step S101. To prevent misjudgment, in a preferred implementation, the preset duration should be longer than the normal heartbeat interval of the SSE connection, and the timestamp can be read again before contention to confirm that the lock identifier has indeed not been updated for a long time. Furthermore, to avoid multiple pages simultaneously determining the original lock is invalid and triggering fierce lock contention, the random duration mechanism in step S1022 can be used to wait for a random duration after determining invalidation before performing the write operation. This fallback mechanism effectively cleans up zombie locks left over from extreme anomalies, ensuring that the global lock identifier can be promptly reclaimed and redistributed under any circumstances.
[0103] This embodiment significantly enhances the fault tolerance and robustness of the global lock management system in extreme scenarios by adding a fallback failure judgment mechanism based on a preset time. This enables non-master pages to proactively detect and intervene, ensuring that even if the master page is completely silent, the one-way service push channel can be re-established after a preset time. Simultaneously, combining the conditions of "no change event detected" and "keys can still be retrieved" in the judgment effectively avoids misjudgments caused by temporary network fluctuations or event loss, improving the accuracy of the judgment logic.
[0104] The above embodiments are merely illustrative of several implementation methods of this application, and their descriptions are relatively specific and detailed, but they should not be construed as limiting the scope of the invention patent. It should be noted that those skilled in the art can make several modifications and improvements without departing from the concept of this application, and this application also intends to include these modifications and variations.
Claims
1. A browser multi-page unidirectional channel management method, characterized in that, Applying this to multiple browser pages under the same domain includes the following steps: When any browser page completes initialization and generates a unique page identifier, the following contention channel steps are executed: read the global lock identifier data stored in the cross-page shared storage and determine whether a valid lock identifier exists; if no valid lock identifier exists, write the page's unique identifier into the cross-page shared storage as a global lock identifier, and construct a single service unidirectional push channel based on the page's runtime context; if a valid lock identifier exists, do not write the page's unique identifier into the cross-page shared storage, and do not construct a single service unidirectional push channel based on the page's runtime context. When the global lock identifier of cross-page shared storage is cleared, a new page unique identifier is generated and the contention channel step is executed; when the global lock identifier of cross-page shared storage is changed and the changed global lock identifier is inconsistent with the page unique identifier of this page, the service one-way push channel built by this page based on the runtime context is destroyed.
2. The browser multi-page unidirectional channel management method according to claim 1, characterized in that, The steps for reading global lock identifier data stored in cross-page shared storage and determining whether a valid lock identifier exists include: If the corresponding key for the global lock identifier is not found in the cross-page shared storage, it is determined that there is no valid lock identifier; If a key corresponding to a storage global lock identifier is found in the cross-page shared storage, and the data within the key does not conform to the page unique identifier format, it is determined that there is no valid lock identifier. If a key corresponding to the storage global lock identifier is found in the cross-page shared storage, and the data within the key matches the page's unique identifier format, then a valid lock identifier is determined to exist.
3. The browser multi-page unidirectional channel management method according to claim 1, characterized in that, The steps for constructing a single service unidirectional push channel based on the runtime context of this page include: Establish an SSE long-lived connection link between this page and the server; use the SSE long-lived connection link as a one-way service push channel for this page.
4. The browser multi-page unidirectional channel management method according to claim 3, characterized in that, After establishing the SSE persistent connection between this page and the server, the following steps are also included: Monitor for abnormal events in the SSE long-lived connection link; When an abnormal interruption is detected in the SSE long-lived connection link, the current SSE long-lived connection link is closed, and the global lock flag stored in the cross-page shared storage is cleared to trigger the cross-page shared storage to output change event data.
5. The browser multi-page unidirectional channel management method according to claim 3, characterized in that, After establishing the SSE persistent connection between this page and the server, the following steps are also included: When the page is detected to be closed or crashes, clear the global lock flag stored in the cross-page shared storage to trigger the cross-page shared storage to output change event data.
6. The browser multi-page unidirectional channel management method according to claim 4 or 5, characterized in that, The steps to clear the global lock icon stored in cross-page shared storage in a browser page include: The browser page sends a clear command to the cross-page shared storage to trigger the cross-page shared storage to respond to the clear command, delete the global lock identifier of the storage, and output change event data to other browser pages of the same domain.
7. The browser multi-page unidirectional channel management method according to claim 1, characterized in that, Following the steps of constructing a single service unidirectional push channel based on the runtime context of this page, the following are included: The service continuously acquires raw message data sent by the server through the one-way push channel; performs unified encapsulation processing on the raw message data to generate cross-page broadcast message data; The cross-page broadcast message data will be synchronously updated to other browser pages of the same domain.
8. The browser multi-page unidirectional channel management method according to claim 7, characterized in that, The steps to synchronize cross-page broadcast message data to other browser pages on the same domain include: Write cross-page broadcast message data to cross-page shared storage; When cross-page shared storage detects written cross-page broadcast message data, it outputs a change notification event to other browser pages on the same domain. When other browser pages on the same domain detect the change notification event, they read the cross-page shared storage to obtain the cross-page broadcast message data.
9. The browser multi-page unidirectional channel management method according to claim 1, characterized in that, The cross-page shared storage refers to a dedicated storage key in the browser's local storage that is bound to the domain name to which the browser page belongs; The steps for reading global lock identifier data stored in cross-page shared storage include: Get the domain information currently accessed by the browser page; Based on the domain name information, determine the corresponding cross-page shared storage; read the global lock identifier data stored in the cross-page shared storage.
10. The browser multi-page unidirectional channel management method according to claim 1, characterized in that, When the global lock identifier for cross-page shared storage is detected to be cleared, a new page-unique identifier is generated and the aforementioned contention channel steps are executed, including: When the global lock identifier for cross-page shared storage is detected to be cleared, wait for a random amount of time, regenerate the unique page identifier, and execute the contention channel step.
