Skip to content

Commit 92140d2

Browse files
crisbetowagnermaciel
authored andcommitted
fix(cdk/layout): breakpoint observer not firing callback on chrome in specific cases (#23571)
There appears to be a bug in Chrome, where if we try to use `matchMedia` on a media query that doesn't match anything on the page and a style recalculation is trigger on the `body`, the `matchMedia` callback stops firing which in turn breaks `BreakpointObserver`. These changes expand an existing workaround that we had for WebKit browsers involving inserting a dummy `style` tag on the page so that there's always at least one matching element. Fixes #23546. (cherry picked from commit cfe79b8)
1 parent 82fd042 commit 92140d2

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/cdk/layout/media-matcher.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,21 @@ export class MediaMatcher {
3535
* MediaQueryList for the query provided.
3636
*/
3737
matchMedia(query: string): MediaQueryList {
38-
if (this._platform.WEBKIT) {
38+
if (this._platform.WEBKIT || this._platform.BLINK) {
3939
createEmptyStyleRule(query);
4040
}
4141
return this._matchMedia(query);
4242
}
4343
}
4444

4545
/**
46-
* For Webkit engines that only trigger the MediaQueryListListener when
47-
* there is at least one CSS selector for the respective media query.
46+
* Creates an empty stylesheet that is used to work around browser inconsistencies related to
47+
* `matchMedia`. At the time of writing, it handles the following cases:
48+
* 1. On WebKit browsers, a media query has to have at least one rule in order for `matchMedia`
49+
* to fire. We work around it by declaring a dummy stylesheet with a `@media` declaration.
50+
* 2. In some cases Blink browsers will stop firing the `matchMedia` listener if none of the rules
51+
* inside the `@media` match existing elements on the page. We work around it by having one rule
52+
* targeting the `body`. See https://github.com/angular/components/issues/23546.
4853
*/
4954
function createEmptyStyleRule(query: string) {
5055
if (mediaQueriesForWebkitCompatibility.has(query)) {
@@ -59,8 +64,7 @@ function createEmptyStyleRule(query: string) {
5964
}
6065

6166
if (mediaQueryStyleNode.sheet) {
62-
(mediaQueryStyleNode.sheet as CSSStyleSheet)
63-
.insertRule(`@media ${query} {.fx-query-test{ }}`, 0);
67+
mediaQueryStyleNode.sheet.insertRule(`@media ${query} {body{ }}`, 0);
6468
mediaQueriesForWebkitCompatibility.add(query);
6569
}
6670
} catch (e) {

0 commit comments

Comments
 (0)