Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,21 @@ player.supports('method', 'getDuration');
player.supports('event', 'ended');
```

`destroy`: void
Stop the player: it no longer handles messages from the iframe, and calls
made afterwards do nothing. Call it when you remove the iframe, for example
when a component unmounts. If you keep the iframe on the page, call `off()`
first so the iframe stops sending events.

```js
// React
useEffect(() => {
const player = new playerjs.Player(iframeRef.current);
player.on('ready', () => player.play());
return () => player.destroy();
}, []);
```

Events
------

Expand Down
99 changes: 99 additions & 0 deletions e2e/api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ declare function whenReady(p: any, ms?: number): Promise<void>;
declare function get(name: string, ms?: number): Promise<any>;
declare function nextEvent(name: string, ms?: number): Promise<any>;
declare function timeout<T>(ms: number, value?: T): Promise<T>;
declare const __received: { origin: string; data: unknown }[];

// Run fn in the page and return what it threw (player.js throws strings).
const thrown = (fn: string) => `(() => { try { (${fn})(); return null; } catch (e) { return { type: typeof e, value: String(e) }; } })()`;
Expand Down Expand Up @@ -236,3 +237,101 @@ test.describe('event listeners', () => {
expect(n).toBe(1);
});
});

test.describe('remounting an embed with the same src', () => {
// As SPA frameworks do: remove the iframe, add a new one with the same src.
// The removed Player used to pick up the new iframe's ready and, before
// #94, crashed sending its queue to a null contentWindow (#93, #75).
const remount = (page: any, destroyFirst: boolean) =>
page.evaluate(async (destroyFirst: boolean) => {
const w = window as any;
const a = addFrame('/e2e/fixtures/mock.html?delay=500');
const old = new playerjs.Player(a);
const counts = { oldReady: 0, oldPlay: 0, newPlay: 0 };
old.on('ready', () => counts.oldReady++);
old.on('play', () => counts.oldPlay++);
old.getDuration(() => {});
await timeout(100);
if (destroyFirst) old.destroy();
a.remove();

const b = addFrame('/e2e/fixtures/mock.html?delay=500');
const p = (w.player = new playerjs.Player(b));
await whenReady(p);
p.on('play', () => counts.newPlay++);
await timeout(100);
p.play();
await timeout(500);
return { ...counts, oldIsReady: old.isReady, newDuration: await get('getDuration') };
}, destroyFirst);

test.beforeEach(async ({ page }) => {
await openParent(page);
});

for (const destroyFirst of [false, true]) {
test(`${destroyFirst ? 'after destroy()' : 'without destroy()'}: no errors and the old player stays asleep`, async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', (e) => errors.push(e.message));
const r = await remount(page, destroyFirst);
expect(errors).toEqual([]);
expect(r).toEqual({ oldReady: 0, oldPlay: 0, newPlay: 1, oldIsReady: false, newDuration: 20 });
});
}
});

test.describe('destroy()', () => {
// Methods that reached the mock receiver, per its raw message log.
const sentToReceiver = (page: any, methods: string[]) =>
childFrame(page, 'mock').evaluate(
(methods: string[]) => __received.map((m) => JSON.parse(m.data as string).method).filter((m) => methods.includes(m)),
methods,
);

test.beforeEach(async ({ page }) => {
await openParent(page);
});

test('stops handling messages and sending calls', async ({ page }) => {
await page.evaluate(() => (window as any).createPlayer('/e2e/fixtures/mock.html'));
const result = page.evaluate(async () => {
const calls = { play: 0, getter: 0, receive: 0 };
player.on('play', () => calls.play++);
await timeout(100);

player.destroy();
player.destroy(); // safe to call twice

// If the window listener were still attached, this would be called.
player.receive = () => calls.receive++;

const send = player.send({ method: 'play' });
player.play();
player.setVolume(10);
player.getDuration(() => calls.getter++);
await timeout(600);
return { send, calls };
});
// A listener-less event from the iframe would reach every play listener.
await page.waitForTimeout(200);
await childFrame(page, 'mock').evaluate(() =>
window.parent.postMessage(JSON.stringify({ context: 'player.js', event: 'play' }), '*'),
);
expect(await result).toEqual({ send: false, calls: { play: 0, getter: 0, receive: 0 } });
expect(await sentToReceiver(page, ['play', 'setVolume', 'getDuration'])).toEqual([]);
});

test('before ready: queued calls are never sent', async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', (e) => errors.push(e.message));
await page.evaluate(async () => {
const p = new playerjs.Player(addFrame('/e2e/fixtures/mock.html?delay=500'));
p.setVolume(42);
p.play();
p.destroy();
await timeout(1000);
});
expect(await sentToReceiver(page, ['setVolume', 'play'])).toEqual([]);
expect(errors).toEqual([]);
});
});
20 changes: 20 additions & 0 deletions e2e/protocol.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,26 @@ test.describe('ready handshake', () => {
});
});

test.describe('several players from the same origin', () => {
// A listener-less ready from one iframe used to fire the ready callbacks
// of every Player on the page from that origin, even ones whose own
// iframe never became ready (README: "inconsistencies if you have
// multiple players on the page").
test("another iframe's ready doesn't fire this player's ready", async ({ page }) => {
await openParent(page);
const r = await page.evaluate(async () => {
const slow = new playerjs.Player(addFrame('/e2e/fixtures/mock.html?delay=60000'));
const fast = new playerjs.Player(addFrame('/e2e/fixtures/mock.html'));
const counts = { slow: 0, fast: 0 };
slow.on('ready', () => counts.slow++);
fast.on('ready', () => counts.fast++);
await timeout(1000);
return { ...counts, slowIsReady: slow.isReady, fastIsReady: fast.isReady };
});
expect(r).toEqual({ slow: 0, fast: 1, slowIsReady: false, fastIsReady: true });
});
});

test.describe('referrer-less iframes', () => {
// Characterization of a security/robustness problem: the Receiver derives
// the parent origin from document.referrer. With no referrer its origin is
Expand Down
38 changes: 31 additions & 7 deletions src/player.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,13 @@ var readiedWindows = typeof WeakSet === 'function' ? new WeakSet() : null;
// Is this ready message from the given iframe? Match the sending window, so
// it works even if the iframe's URL has changed since src was set. Matching
// the src the receiver reports is kept so nothing that worked before breaks.
// An iframe that has been removed from the page has no window and can't be
// the sender, so a stale Player doesn't pick up a new iframe's ready (#93).
function isFromFrame(e, data, elem) {
if (e.source && elem.contentWindow && e.source === elem.contentWindow) {
if (!elem.contentWindow) {
return false;
}
if (e.source === elem.contentWindow) {
return true;
}
return !!(data.value && data.value.src === elem.src);
Expand Down Expand Up @@ -108,10 +113,11 @@ playerjs.Player.prototype.init = function(elem, options){
this.methods = playerjs.METHODS.all();

if (playerjs.POST_MESSAGE){
// Set up the reciever.
playerjs.addEvent(window, 'message', function(e){
// Set up the reciever. Keep a reference so destroy() can remove it.
this._onMessage = function(e){
self.receive(e);
});
};
playerjs.addEvent(window, 'message', this._onMessage);
} else {
playerjs.log('Post Message is not Available.');
}
Expand All @@ -129,6 +135,10 @@ playerjs.Player.prototype.init = function(elem, options){
};

playerjs.Player.prototype.send = function(data, callback, ctx){
if (this.destroyed){
return false;
}

// Add the context and version to the data.
data.context = playerjs.CONTEXT;
data.version = playerjs.VERSION;
Expand Down Expand Up @@ -180,9 +190,16 @@ playerjs.Player.prototype.receive = function(e){
return false;
}

// We need to determine if we are ready.
if (data.event === 'ready' && data.value && isFromFrame(e, data, this.elem)){
this.ready(data);
// We need to determine if we are ready. A ready from any other iframe
// (another player, or a new iframe after ours was removed) is not ours:
// ignore it so it doesn't fire our ready callbacks.
if (data.event === 'ready'){
if (!isFromFrame(e, data, this.elem)){
return false;
}
if (data.value){
this.ready(data);
}
}

if (this.keeper.has(data.event, data.listener)){
Expand Down Expand Up @@ -259,6 +276,13 @@ playerjs.Player.prototype.off = function(event, callback){
return listeners.length > 0;
};

// Stop the player handling messages and sending calls, e.g. when the iframe
// is removed. Safe to call more than once.
playerjs.Player.prototype.destroy = function(){
window.removeEventListener('message', this._onMessage, false);
this.destroyed = true;
};

// Based on what ready passed back, we can determine if the events/method are
// supported by the player.
playerjs.Player.prototype.supports = function(evtOrMethod, names){
Expand Down
Loading