2018-10-10 17:26:24 +00:00
|
|
|
/* global promisify CHROME URLS */
|
|
|
|
/* exported navigatorUtil */
|
2018-10-07 13:20:39 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const navigatorUtil = (() => {
|
|
|
|
const handler = {
|
|
|
|
urlChange: null
|
|
|
|
};
|
|
|
|
const tabGet = promisify(chrome.tabs.get.bind(chrome.tabs));
|
|
|
|
return extendNative({onUrlChange});
|
|
|
|
|
|
|
|
function onUrlChange(fn) {
|
|
|
|
initUrlChange();
|
|
|
|
handler.urlChange.push(fn);
|
|
|
|
}
|
|
|
|
|
|
|
|
function initUrlChange() {
|
2018-10-09 15:38:29 +00:00
|
|
|
if (handler.urlChange) {
|
2018-10-07 13:20:39 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
handler.urlChange = [];
|
|
|
|
|
|
|
|
chrome.webNavigation.onCommitted.addListener(data =>
|
|
|
|
fixNTPUrl(data)
|
2018-10-07 13:28:51 +00:00
|
|
|
.then(() => executeCallbacks(handler.urlChange, data, 'committed'))
|
|
|
|
);
|
2018-10-07 13:20:39 +00:00
|
|
|
|
|
|
|
chrome.webNavigation.onHistoryStateUpdated.addListener(data =>
|
|
|
|
fixNTPUrl(data)
|
2018-10-07 13:28:51 +00:00
|
|
|
.then(() => executeCallbacks(handler.urlChange, data, 'historyStateUpdated'))
|
|
|
|
);
|
2018-10-07 13:20:39 +00:00
|
|
|
|
|
|
|
chrome.webNavigation.onReferenceFragmentUpdated.addListener(data =>
|
|
|
|
fixNTPUrl(data)
|
2018-10-07 13:28:51 +00:00
|
|
|
.then(() => executeCallbacks(handler.urlChange, data, 'referenceFragmentUpdated'))
|
|
|
|
);
|
2018-10-07 13:20:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function fixNTPUrl(data) {
|
|
|
|
if (
|
|
|
|
!CHROME ||
|
|
|
|
!URLS.chromeProtectsNTP ||
|
|
|
|
!data.url.startsWith('https://www.google.') ||
|
|
|
|
!data.url.includes('/_/chrome/newtab?')
|
|
|
|
) {
|
|
|
|
return Promise.resolve();
|
|
|
|
}
|
|
|
|
return tabGet(data.tabId)
|
|
|
|
.then(tab => {
|
|
|
|
if (tab.url === 'chrome://newtab/') {
|
|
|
|
data.url = tab.url;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function executeCallbacks(callbacks, data, type) {
|
|
|
|
for (const cb of callbacks) {
|
|
|
|
cb(data, type);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function extendNative(target) {
|
|
|
|
return new Proxy(target, {
|
|
|
|
get: (target, prop) => {
|
|
|
|
if (target[prop]) {
|
|
|
|
return target[prop];
|
|
|
|
}
|
|
|
|
return chrome.webNavigation[prop].addListener.bind(chrome.webNavigation[prop]);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
})();
|