检测是否启用了镶板

4 html javascript google-chrome google-chrome-extension

我想在javascript中检测是否在chrome中启用了面板.

目前,您可以使用以下代码创建面板:

chrome.windows.create({ url: "[url]", width: 500, height: 516, type: 'panel'});
Run Code Online (Sandbox Code Playgroud)

当Chrome中的面板被禁用时,它会打开一个弹出窗口.但问题是每个chrome版本都没有启用面板.但是人们可以在chrome:// flags上手动启用它.因此,当禁用标志时,我想将人们重定向到该页面,以便他们可以启用面板.

Rob*_*b W 12

您可以使用alwaysOnTop回调中的boolean属性检测打开的窗口是否是面板chrome.windows.create:

chrome.windows.create({
    url: '...url...', // ...
    type: 'panel'
}, function(windowInfo) {
    // if  windowInfo.alwaysOnTop  is  true  , then it's a panel.
    // Otherwise, it is just a popup
});
Run Code Online (Sandbox Code Playgroud)

如果要检测是否启用了标志,请创建窗口,读取值,然后将其删除.由于创建过程是异步的,因此必须使用回调来实现值检索.

var _isPanelEnabled;
var _isPanelEnabledQueue = [];
function getPanelFlagState(callback) {
    if (typeof callback != 'function') throw Error('callback function required');
    if (typeof _isPanelEnabled == 'boolean') {
        callback(_isPanelEnabled); // Use cached result
        return;
    }
    _isPanelEnabledQueue.push(callback);

    if (_isPanelEnabled == 'checking')
        return;

    _isPanelEnabled = 'checking';
    chrome.windows.create({
        url: 'about:blank',
        type: 'panel'
    }, function(windowInfo) {
        _isPanelEnabled = windowInfo.alwaysOnTop;
        chrome.windows.remove(windowInfo.id);

        // Handle all queued callbacks
        while (callback = _isPanelEnabledQueue.shift()) {
            callback(windowInfo.alwaysOnTop);
        }
    });
}
// Usage:
getPanelFlagState(function(isEnabled) {
    alert('Panels are ' + isEnabled);
});
Run Code Online (Sandbox Code Playgroud)

因为只能通过重新加载Chrome浏览器来切换标志,所以缓存标志的值是有意义的(如函数所示).为确保窗口创建测试仅发生一次,回调将排队.