Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a chrome browser tab via terminal?

Currently I am writing a script that invokes a new instance of the chrome browser.

I know how to call chrome to open a *.html document in a new tab.

google-chrome *.html   

Chrome will open a new tab to show that file.

How can I close the tab in terminal without closing other tabs or closing the browser window?

like image 552
luoluo Avatar asked Nov 01 '22 09:11

luoluo


2 Answers

only linux answer:

Perhaps wmctrl could be of some assistance. You could use the -c option that closes a window gracefully:

wmctrl -c "tab title"

The string chrome is matched against the window titles. Note that the window might not close if some message pops-up (e.g. when you have multiple tabs open).

like image 152
Liam Avatar answered Nov 09 '22 10:11

Liam


You can look into chrome remote debugging:

chromium --remote-debugging-port=9222

and connect to it with some kind of client ( https://github.com/cyrus-and/chrome-remote-interface seems good). The debug protocol is used for a number of applications, but with some work you can achieve the kind of functionality you want. Here are some docs for you to check out: https://chromedevtools.github.io/devtools-protocol/tot/Page

Or perhaps chromix-too, which is based on an extension, daemon and client architecture.

https://github.com/smblott-github/chromix-too

This seems to be much easier to use, and might be exactly what you want, though the extension is a bit inconvenient, and there seems to be demand for more capabilities to be supported.

EDIT The query you would be looking for is:

        const chrome = require('ox-chrome-remote-interface'); 
        chrome.List().then(tabs=>{
            const list = tabs
                .filter(t=>t.type == 'page' &&  t.title.includes(TITLE))
                .map(t => t.id)
            if(list.length==1){
                chrome.Close({id:list[0]})
            } else {
                console.error(`${list.length} tabs match.`)
            }
        })
like image 24
M3D Avatar answered Nov 09 '22 09:11

M3D