From df66ebd82a1daa034823a05f58880049ea7e388d Mon Sep 17 00:00:00 2001 From: Demetrio Girardi Date: Thu, 3 Oct 2024 07:45:07 -0700 Subject: [PATCH] Fix exception on __pb_locator__ lookup (#236) --- src/messaging.js | 6 ++++-- test/spec/messaging_spec.js | 33 ++++++++++++++++++++++++--------- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/src/messaging.js b/src/messaging.js index c047fff..58a43c4 100644 --- a/src/messaging.js +++ b/src/messaging.js @@ -14,8 +14,10 @@ export function prebidMessenger(publisherURL, win = window) { } let target = win.parent; - while (target != null && target !== win.top && !isPrebidWindow(target)) target = target.parent; - if (!isPrebidWindow(target)) target = win.parent; + try { + while (target != null && target !== win.top && !isPrebidWindow(target)) target = target.parent; + if (!isPrebidWindow(target)) target = win.parent; + } catch (e) {} return function sendMessage(message, onResponse) { if (prebidDomain == null) { diff --git a/test/spec/messaging_spec.js b/test/spec/messaging_spec.js index 71b7879..a7dd94b 100644 --- a/test/spec/messaging_spec.js +++ b/test/spec/messaging_spec.js @@ -67,21 +67,36 @@ describe('prebidMessenger',() => { } }; }) - it('should post to first ancestor that has a __pb_locator__ child', () => { - [target, target.parent].forEach(win => { - win.frames = { - __pb_locator__: {} - }; + Object.entries({ + throws() { throw new DOMException() }, + 'does not throw'() { return {} } + }).forEach(([t, getFrames]) => { + describe(`when ancestor ${t}`, () => { + beforeEach(() => { + Object.defineProperty(target.parent.parent, 'frames', {get: getFrames}); + }) + it('should post to first ancestor that has a __pb_locator__ child', () => { + [target, target.parent].forEach(win => { + win.frames = { + __pb_locator__: {} + }; + }) + sendMessage('test'); + sinon.assert.called(target.postMessage); + }); }) - sendMessage('test'); - sinon.assert.calledWith(target.postMessage); - }); + }) it('should post to immediate parent when no ancestor has __pb_locator__', () => { win.parent.postMessage = sinon.spy(); delete target.postMessage; sendMessage('test'); - sinon.assert.calledWith(win.parent.postMessage); + sinon.assert.called(win.parent.postMessage); }); + it('should post to first restricted frame if no __pb_locator__ can be found', () => { + Object.defineProperty(target, 'frames', {get() { throw new DOMException() }}); + sendMessage('test'); + sinon.assert.called(target.postMessage) + }) }); it('should not run callback on response if origin does not mach', ()=> {