From 367cdd666669267ffa2657dd53beec6006da32b3 Mon Sep 17 00:00:00 2001 From: Raymond Hill Date: Sat, 27 Apr 2019 13:12:33 -0400 Subject: [PATCH] Make use of `X-DNS-Prefetch-Control` in Chromium-based browsers Related issue: - https://github.com/uBlockOrigin/uBlock-issues/issues/548 The fix applies only to Chromium-based browsers -- a `X-DNS-Prefetch-Control` header[1] will be unconditionally injected when uBO's "Disable pre-fetching" setting is enabled (it is by default). This is a mitigation, this does not completely fix the issue of the setting "Disable pre-fetching" being disregarded on Chromium-based browsers when sites use `preconnect`/`preload`. [1] https://developer.mozilla.org/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control --- platform/chromium/vapi-background.js | 6 ++++- platform/chromium/vapi-webrequest.js | 36 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/platform/chromium/vapi-background.js b/platform/chromium/vapi-background.js index b41057ea2..5688f935d 100644 --- a/platform/chromium/vapi-background.js +++ b/platform/chromium/vapi-background.js @@ -223,8 +223,9 @@ vAPI.browserSettings = (function() { } switch ( setting ) { case 'prefetching': + const enabled = !!details[setting]; try { - if ( !!details[setting] ) { + if ( enabled ) { chrome.privacy.network.networkPredictionEnabled.clear({ scope: 'regular' }, vAPI.resetLastError); @@ -237,6 +238,9 @@ vAPI.browserSettings = (function() { } catch(ex) { console.error(ex); } + if ( vAPI.prefetching instanceof Function ) { + vAPI.prefetching(enabled); + } break; case 'hyperlinkAuditing': diff --git a/platform/chromium/vapi-webrequest.js b/platform/chromium/vapi-webrequest.js index 2fce34869..7f9026ef8 100644 --- a/platform/chromium/vapi-webrequest.js +++ b/platform/chromium/vapi-webrequest.js @@ -195,3 +195,39 @@ vAPI.net.onBeforeReady = vAPI.net.onBeforeReady || (function() { })(); /******************************************************************************/ + +// https://github.com/uBlockOrigin/uBlock-issues/issues/548 +// Use `X-DNS-Prefetch-Control` to workaround Chromium's disregard of the +// setting "Predict network actions to improve page load performance". + +vAPI.prefetching = (function() { + let listening = false; + + const onHeadersReceived = function(details) { + details.responseHeaders.push({ + name: 'X-DNS-Prefetch-Control', + value: 'off' + }); + return { responseHeaders: details.responseHeaders }; + }; + + return state => { + const wr = chrome.webRequest; + if ( state && listening ) { + wr.onHeadersReceived.removeListener(onHeadersReceived); + listening = false; + } else if ( !state && !listening ) { + wr.onHeadersReceived.addListener( + onHeadersReceived, + { + urls: [ 'http://*/*', 'https://*/*' ], + types: [ 'main_frame', 'sub_frame' ] + }, + [ 'blocking', 'responseHeaders' ] + ); + listening = true; + } + }; +})(); + +/******************************************************************************/