Skip to content

Commit

Permalink
Apply matchMedia to the top frame (prebid#3612)
Browse files Browse the repository at this point in the history
* Apply matchMedia to the top frame

In case Prebid.js is called from within an iFrame, matchMedia should be applied to window.top, not the containing iFrame.
This PR falls back to the legacy behavior in case of unfriendly iFrames.

* Spec update
  • Loading branch information
benjaminclot authored and mike-chowla committed Mar 11, 2019
1 parent 16e5e16 commit 0b39298
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/sizeMapping.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { config } from './config';
import {logWarn, isPlainObject, deepAccess, deepClone} from './utils';
import {logWarn, isPlainObject, deepAccess, deepClone, getWindowTop} from './utils';
import includes from 'core-js/library/fn/array/includes';

let sizeConfig = [];
Expand Down Expand Up @@ -123,7 +123,17 @@ function evaluateSizeConfig(configs) {
typeof config === 'object' &&
typeof config.mediaQuery === 'string'
) {
if (matchMedia(config.mediaQuery).matches) {
let ruleMatch = false;

try {
ruleMatch = getWindowTop().matchMedia(config.mediaQuery).matches;
} catch (e) {
logWarn('Unfriendly iFrame blocks sizeConfig from being correctly evaluated');

ruleMatch = matchMedia(config.mediaQuery).matches;
}

if (ruleMatch) {
if (Array.isArray(config.sizesSupported)) {
results.shouldFilter = true;
}
Expand Down
7 changes: 7 additions & 0 deletions test/spec/sizeMapping_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ describe('sizeMapping', function () {

matchMediaOverride = {matches: false};

sandbox.stub(utils.getWindowTop(), 'matchMedia').callsFake((...args) => {
if (typeof matchMediaOverride === 'function') {
return matchMediaOverride.apply(utils.getWindowTop(), args);
}
return matchMediaOverride;
});

sandbox.stub(window, 'matchMedia').callsFake((...args) => {
if (typeof matchMediaOverride === 'function') {
return matchMediaOverride.apply(window, args);
Expand Down

0 comments on commit 0b39298

Please sign in to comment.