简体   繁体   中英

How to prevent new tab creation in puppeteer's chromium instance?

I would like to prevent new tab creation. Either by clicking 'new tab button' either by window.open method. Is there any way to listen on new tab creation. I don't mean 'targetcreated' event because then tab is already created. Maybe there is something similar to event.preventDefault?

Below is a very simple code that closes every new tab but I think it's very ugly and I want to improve it.

browser.on('targetcreated', (target) => {
    function closeNewTabs(target) {
      let targetBrowser = target.browser();
      targetBrowser.pages().then(data => {
          if (data.length>1) {
              for (let i = 0; i < data.length; i++) {
                  if (i>1) data[i].close();
              }
          }
      })
    }
})

A possible workaround would be to listen to targetcreated event and then page.close

It would be something similar to

browser.on("targetcreated", async (target)=>{
   const page=await target.page();
   if(page) page.close();
});

It doesn't prevent creating new tabs, but it should close them immediately after opening

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM