How to detect if a user is using tracking protection in Firefox 42+

為{幸葍}努か 提交于 2019-12-03 02:27:42

navigator.donottrack only shows the setting of the "Do not track" preference. It does not tell if tracking protection, which is a different feature, is enabled. Tracking protection is enabled automatically when in private browsing mode, but users can change a setting in about:config to have it enabled full time.

While you can't tell directly if the feature is enabled, you can check for its effects with something like this:

var canreach = false;
$(function() {
    $('<img/>')
        .attr("src", "//apps.facebook.com/favicon.ico")
        .load(function(){canreach = true;})
        .css("display", "none")
        .appendTo(document.body);
});

Firefox uses a list obtained from Disconnect for its tracking protection; just use a domain that you know is on that list, and an image that you know will exist.

Of course, this could flag any number of causes for the image not to load, including network connectivity problems, ad blocking software, filtering proxies, etc.

SleepWalker

Here is slightly improved version of miken32's answer using Deferred:

function whenNoTrackingProtection() {
    if (!whenNoTrackingProtection.promise) {
        var dfd = new $.Deferred();
        whenNoTrackingProtection.promise = dfd.promise();

        var time = Date.now();
        $('<img/>')
            .attr('src', '//apps.facebook.com/favicon.ico')
            .on('load', dfd.resolve)
            .on('error', function() {
                if ((Date.now() - time) < 50) {
                    dfd.reject();
                } else {
                    // The request took to long, it seems this is a network error.
                    dfd.resolve();
                }
            });
    }

    return whenNoTrackingProtection.promise;
}

or without jQuery, using Promise:

function whenNoTrackingProtection() {
    if (!whenNoTrackingProtection.promise) {
        whenNoTrackingProtection.promise = new Promise(function(resolve, reject) {
            var time = Date.now();
            var img = new Image();
            img.onload = resolve;
            img.onerror = function() {
                if ((Date.now() - time) < 50) {
                    reject();
                } else {
                    // The request took to long, it seems this is a network error.
                    resolve();
                }
            };
            img.src = '//apps.facebook.com/favicon.ico';
        });
    }

    return whenNoTrackingProtection.promise;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!