Is it possible to detect when a user switches tabs

2019-04-11 01:38发布

问题:

In particular, I am interested to know if it is possible to capture a user's click to a different browser tab. I guess technically I could get the blur and focus of the window object but if there was something more closely tied to the browser (IE, FF, Chrome, etc.) that would be even better.

回答1:

IE

If you are writing native code (i.e. a browser plug-in) you can use DWebBrowserEvents2::WindowStateChanged.

Here is some sample code, for your IDispatch::Invoke() implementation:

    // DWebBrowserEvents2
    case DISPID_WINDOWSTATECHANGED: {
        if (pDispParams) {
            DWORD dwMask  = pDispParams->rgvarg[0].lVal;
            DWORD dwFlags = pDispParams->rgvarg[1].lVal;

            // We only care about WINDOWSTATE_USERVISIBLE.
            if (dwMask & OLECMDIDF_WINDOWSTATE_USERVISIBLE)
            {
                bool visible = !!(dwFlags & OLECMDIDF_WINDOWSTATE_USERVISIBLE));

                // ... your code here ...
            }
        }
        break;
    }

There is no explicit event sent to the Javascript of the page, but the blur event may do what you desire.

Firefox

In Firefox you can detect tab changes in your XUL by adding an event listener for TabAttrModified and inspecting the selected attribute. See the MDC documentation for the dealing with the Tabbed Browser.