feat(targets): add target.opener() (#2641)

This adds a `.opener` property to a target so that its origin can be tracked.
For now returns `null` when there's no `openerId`.

Fixes #1830
This commit is contained in:
Jan Potoms 2018-06-01 02:06:29 +02:00 committed by Andrey Lushnikov
parent 0b94fa70eb
commit f6356683cd
5 changed files with 46 additions and 0 deletions

View File

@ -260,6 +260,7 @@
* [target.browser()](#targetbrowser)
* [target.browserContext()](#targetbrowsercontext)
* [target.createCDPSession()](#targetcreatecdpsession)
* [target.opener()](#targetopener)
* [target.page()](#targetpage)
* [target.type()](#targettype)
* [target.url()](#targeturl)
@ -2808,6 +2809,11 @@ The browser context the target belongs to.
Creates a Chrome Devtools Protocol session attached to the target.
#### target.opener()
- returns: <?[Target]>
Get the target that opened this target. Top-level targets return `null`.
#### target.page()
- returns: <[Promise]<?[Page]>>

View File

@ -76,6 +76,16 @@ class Target {
return this._browserContext;
}
/**
* @return {Puppeteer.Target}
*/
opener() {
const { openerId } = this._targetInfo;
if (!openerId)
return null;
return this.browser()._targets.get(openerId);
}
/**
* @param {!Protocol.Target.TargetInfo} targetInfo
*/

View File

@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<title>Popup</title>
</head>
<body>
I am a popup
</body>
</html>

View File

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>Popup test</title>
</head>
<body>
<script>
window.open('./popup.html');
</script>
</body>
</html>

View File

@ -139,5 +139,15 @@ module.exports.addTests = function({testRunner, expect, puppeteer, browserWithEx
// Cleanup.
await newPage.close();
});
it('should have an opener', async({page, server, browser}) => {
await page.goto(server.EMPTY_PAGE);
const [createdTarget] = await Promise.all([
new Promise(fulfill => browser.once('targetcreated', target => fulfill(target))),
page.goto(server.PREFIX + '/popup/window-open.html')
]);
expect((await createdTarget.page()).url()).toBe(server.PREFIX + '/popup/popup.html');
expect(createdTarget.opener()).toBe(page.target());
expect(page.target().opener()).toBe(null);
});
});
};