I'm struggling to figure how to:
- Detect when a new tab is opened in chrome (e.g. from clicking something on a page)
- Get the url of that newly opened tab.
I have connected pyppeteer to my current chrome instance with this:
browser = await pyppeteer.connect(browserURL='http://127.0.0.1:9222')
And when I create a tab manually I have no problem getting the url.
url = 'https://www.google.com'
page = await browser.newPage()
await page.goto(url)
current_url = await page.evaluate('window.location.href', force_expr=True)
I have read that there is a way to do this in the original puppeteer with 'targetcreated':
browser.on('targetcreated', function(){
console.log('New Tab Created');
})
So I'm asking how can I do something like:
// listen for new tab
newTab = browser.on('targetcreated') // This is where I'm stuck
// get url
current_url = await newTab.evaluate('window.location.href', force_expr=True)
I hope that all makes sense!
You need to add a callback function like in your JavaScript example:
The
about:blank
url was printed when a new blank tab was opened withbrowser.newPage()
.Pyppeteer is using pyee.BaseEventEmitter.on under the hood.