Skip to content

Commit 1668e97

Browse files
authored
fix: make MediaPlayerFactory SSR-safe to prevent "window is not defined" error (Dash-Industry-Forum#4929)
Wrap the auto-creation logic in a browser environment check to allow dash.js to be imported in SSR environments like Next.js without throwing a "window is not defined" error. The module-level code that accesses window APIs (addEventListener, setInterval, etc.) is now only executed when running in a browser context. Fixes Dash-Industry-Forum#4728
1 parent 20b8441 commit 1668e97

File tree

1 file changed

+21
-17
lines changed

1 file changed

+21
-17
lines changed

src/streaming/MediaPlayerFactory.js

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -103,32 +103,36 @@ function MediaPlayerFactory() {
103103
}
104104

105105
let instance = MediaPlayerFactory();
106-
let loadInterval;
107106

108-
function loadHandler() {
109-
window.removeEventListener('load', loadHandler);
110-
instance.createAll();
111-
}
107+
// Only execute auto-creation logic in browser environment (SSR-safe)
108+
if (typeof window !== 'undefined' && window) {
109+
let loadInterval;
112110

113-
function loadIntervalHandler() {
114-
if (window.dashjs) {
115-
window.clearInterval(loadInterval);
111+
function loadHandler() {
112+
window.removeEventListener('load', loadHandler);
116113
instance.createAll();
117114
}
118-
}
119115

120-
let avoidAutoCreate = typeof window !== 'undefined' && window && window.dashjs && window.dashjs.skipAutoCreate;
121-
122-
if (!avoidAutoCreate && typeof window !== 'undefined' && window && window.addEventListener) {
123-
if (window.document.readyState === 'complete') {
116+
function loadIntervalHandler() {
124117
if (window.dashjs) {
118+
window.clearInterval(loadInterval);
125119
instance.createAll();
120+
}
121+
}
122+
123+
let avoidAutoCreate = window.dashjs && window.dashjs.skipAutoCreate;
124+
125+
if (!avoidAutoCreate && window.addEventListener) {
126+
if (window.document.readyState === 'complete') {
127+
if (window.dashjs) {
128+
instance.createAll();
129+
} else {
130+
// If loaded asynchronously, window.readyState may be 'complete' even if dashjs hasn't loaded yet
131+
loadInterval = window.setInterval(loadIntervalHandler, 500);
132+
}
126133
} else {
127-
// If loaded asynchronously, window.readyState may be 'complete' even if dashjs hasn't loaded yet
128-
loadInterval = window.setInterval(loadIntervalHandler, 500);
134+
window.addEventListener('load', loadHandler);
129135
}
130-
} else {
131-
window.addEventListener('load', loadHandler);
132136
}
133137
}
134138

0 commit comments

Comments
 (0)