Fix err handler (popup), catch +1 error (promise), check settings control in debug and popup, restyle

This commit is contained in:
Ilya Ig. Petrov 2016-11-21 07:03:02 -08:00
parent b56a1f2484
commit 403c8e47b7
10 changed files with 118 additions and 48 deletions

View File

@ -155,7 +155,8 @@
(pushErr) => cb(pacErr || ipsErr || pushErr, pacRes) (pushErr) => cb(pacErr || ipsErr || pushErr, pacRes)
); );
} },
cb
); );
}, },
@ -346,6 +347,37 @@
} }
function setPac(pacData, cb) {
const config = {
mode: 'pac_script',
pacScript: {
mandatory: false,
data: pacData
}
};
console.log('Setting chrome proxy settings...');
chrome.proxy.settings.set( {value: config}, () => {
const err = checkChromeError();
if (err) {
return cb(err);
}
chrome.proxy.settings.get({}, (details) => {
const ifThis = details.levelOfControl.startsWith('controlled_by_this');
if (!ifThis) {
console.warn('Failed, other extension is in control.');
return cb({clarification: {message:'Настройки прокси контролирует другое расширение. <a href="chrome://settings/search#proxy">Какое?</a>'}});
}
console.log('Successfuly set PAC in proxy settings..');
return cb();
});
});
}
function httpGet(url, cb) { function httpGet(url, cb) {
const start = Date.now(); const start = Date.now();
@ -518,16 +550,7 @@
}; };
return cb(err); return cb(err);
} }
setPac(pacData, cb);
const config = {
mode: 'pac_script',
pacScript: {
mandatory: false,
data: pacData
}
};
console.log('Setting chrome proxy settings...');
chrome.proxy.settings.set( {value: config}, chromified(cb) );
} }
); );
@ -548,3 +571,9 @@ window.addEventListener('unhandledrejection', (event) => {
throw event.reason; throw event.reason;
}); });
chrome.proxy.settings.onChange.addListener((details) => {
console.log('Settings changed:', details);
});

View File

@ -50,8 +50,9 @@
<div id="status">Загрузка...</div> <div id="status">Загрузка...</div>
<footer> <footer>
<input type="button" value="Готово" class="close-button"> <input type="button" value="Готово" class="close-button">
<a id="debug-link" href style="float: right; text-decoration: none">Отладка</a> <a href="../debug/index.html" style="float: right; text-decoration: none">Отладка</a>
</footer> </footer>
<script src="./index.js"></script> <script src="./index.js"></script>
<script src="./keep-links-clickable.js"></script>
</body> </body>
</html> </html>

View File

@ -1,29 +1,27 @@
'use strict'; 'use strict';
chrome.runtime.getBackgroundPage( backgroundPage => { chrome.runtime.getBackgroundPage( (backgroundPage) => {
function getStatus() { const getStatus = () => document.querySelector('#status');
return document.querySelector('#status'); const setStatusTo = (msg) => {
}
function setStatusTo(msg) {
const status = getStatus(); const status = getStatus();
if (msg) { if (msg) {
status.classList.remove('off'); status.classList.remove('off');
status.innerHTML = msg; status.innerHTML = msg;
} else
status.classList.add('off');
} }
else {
status.classList.add('off');
}
};
const antiCensorRu = backgroundPage.antiCensorRu; const antiCensorRu = backgroundPage.antiCensorRu;
// SET DATE // SET DATE
function setDate() { const setDate = () => {
let dateForUser = 'никогда'; let dateForUser = 'никогда';
if( antiCensorRu.lastPacUpdateStamp ) { if( antiCensorRu.lastPacUpdateStamp ) {
@ -52,7 +50,7 @@ chrome.runtime.getBackgroundPage( backgroundPage => {
dateElement.innerText = dateForUser; dateElement.innerText = dateForUser;
dateElement.title = new Date(antiCensorRu.lastPacUpdateStamp).toLocaleString('ru-RU'); dateElement.title = new Date(antiCensorRu.lastPacUpdateStamp).toLocaleString('ru-RU');
} };
setDate(); setDate();
chrome.storage.onChanged.addListener( (changes) => changes.lastPacUpdateStamp.newValue && setDate() ); chrome.storage.onChanged.addListener( (changes) => changes.lastPacUpdateStamp.newValue && setDate() );
@ -83,12 +81,12 @@ chrome.runtime.getBackgroundPage( backgroundPage => {
} }
const ul = document.querySelector('#list-of-providers'); const ul = document.querySelector('#list-of-providers');
//const _firstChild = ul.firstChild; const _firstChild = ul.firstChild;
for( const providerKey of Object.keys(antiCensorRu.pacProviders) ) { for( const providerKey of Object.keys(antiCensorRu.pacProviders).sort() ) {
const li = document.createElement('li'); const li = document.createElement('li');
li.innerHTML = '<input type="radio" name="pacProvider" id="' + providerKey + '"> <label for="' + providerKey + '">'+providerKey + '</label> <a href class="link-button checked-radio-panel">[обновить]</a>'; li.innerHTML = '<input type="radio" name="pacProvider" id="' + providerKey + '"> <label for="' + providerKey + '">'+providerKey + '</label> <a href class="link-button checked-radio-panel">[обновить]</a>';
li.querySelector('.link-button').onclick = () => { triggerChosenProvider(); return false; }; li.querySelector('.link-button').onclick = () => { triggerChosenProvider(); return false; };
ul.insertBefore( li, ul.firstChild ); ul.insertBefore( li, _firstChild );
} }
const radios = [].slice.apply( document.querySelectorAll('[name=pacProvider]') ); const radios = [].slice.apply( document.querySelectorAll('[name=pacProvider]') );
@ -99,12 +97,15 @@ chrome.runtime.getBackgroundPage( backgroundPage => {
if (pacKey === 'none') if (pacKey === 'none')
return antiCensorRu.clearPac(); return antiCensorRu.clearPac();
function enableDisableInputs() { const enableDisableInputs = function () {
const inputs = document.querySelectorAll('input'); const inputs = document.querySelectorAll('input');
for (const i = 0; i < inputs.length; i++) for ( let i = 0; i < inputs.length; i++ ) {
inputs[i].disabled = !inputs[i].disabled; inputs[i].disabled = !inputs[i].disabled;
} }
}
enableDisableInputs(); enableDisableInputs();
setStatusTo('Установка...'); setStatusTo('Установка...');
antiCensorRu.installPac(pacKey, (err) => { antiCensorRu.installPac(pacKey, (err) => {
@ -120,31 +121,27 @@ chrome.runtime.getBackgroundPage( backgroundPage => {
let clarification = err.clarification; let clarification = err.clarification;
do { do {
message = message +' '+ (clarification && clarification.message || err.message || ''); message = message +' '+ (clarification && clarification.message || err.message || '');
clarification = clarification.prev; clarification = clarification && clarification.prev;
} while( clarification ); } while( clarification );
message = message.trim(); message = message.trim();
setStatusTo( setStatusTo(
`<span style="color:red">${ifNotCritical ? 'Некритичная ошибка.' : 'Ошибка!'}</span> `<span style="color:red">${ifNotCritical ? 'Некритичная ошибка.' : 'Ошибка!'}</span>
<br/> <br/>
<span style="font-size: 0.9em; color: darkred">${message}</span> <span style="font-size: 0.9em; color: darkred">${message}</span>
<button>Сообщить автору</button><br/>
<a href class="link-button">[Ещё&nbsp;подробнее]</a>` <a href class="link-button">[Ещё&nbsp;подробнее]</a>`
); );
getStatus().querySelector('.link-button').onclick = function() { getStatus().querySelector('.link-button').onclick = function() {
const div = document.createElement('div'); const div = document.createElement('div');
backgroundPage.console.log('ERROR', err);
div.innerHTML = ` div.innerHTML = `
Более подробную информацию можно узнать из логов фоновой страницы:<br/> Более подробную информацию можно узнать из логов фоновой страницы:<br/>
<a href class="ext">chrome://extensions</a> Это расширение Отладка страниц: фоновая страница Console (DevTools) <a href="chrome://extensions?id=${chrome.runtime.id}" data-in-bg="true">chrome://extensions</a> Это расширение Отладка страниц: фоновая страница Console (DevTools)
<br> <br>
Ещё: ${JSON.stringify({err: err, stack: err.stack})} Ещё: ${JSON.stringify({err: err, stack: err.stack})}
`; `;
getStatus().replaceChild(div, this); getStatus().replaceChild(div, this);
div.querySelector('.ext').onclick = () => {
chrome.tabs.create({ url: 'chrome://extensions?id='+ chrome.runtime.id });
return false;
}
return false; return false;
}; };
@ -156,11 +153,8 @@ chrome.runtime.getBackgroundPage( backgroundPage => {
setStatusTo(''); setStatusTo('');
checkChosenProvider(); checkChosenProvider();
if (antiCensorRu.ifFirstInstall) if (antiCensorRu.ifFirstInstall) {
triggerChosenProvider(); triggerChosenProvider();
}
// Debug
document.querySelector('#debug-link').onclick = () => chrome.tabs.create({ url: chrome.extension.getURL('./pages/debug/index.html') });
}); });

View File

@ -0,0 +1,29 @@
'use strict';
/*
In popup links are not clickable at all, fix it.
On other pages "chrome://" links are not clickable, fix it.
Use only if really required because of performance penalty.
*/
const target = document.getElementById('status');
const updateLinks = () => {
const links = document.querySelectorAll('a:not([href=""])');
for (let i = 0; i < links.length; i++) {
const ln = links[i];
const location = ln.href;
ln.onclick = function () {
chrome.tabs.create({ active: !this.dataset.inBg, url: location });
return false;
};
}
};
new MutationObserver( updateLinks )
.observe(target, { attributes: false, subtree: true, childList: true, characterData: false });
document.addEventListener('DOMContentLoaded', updateLinks);

View File

@ -18,7 +18,10 @@
height: 100%; height: 100%;
} }
nav { nav {
text-align: center; padding: 0.2em;
}
#status {
padding-left: 0.5em;
} }
</style> </style>
</head> </head>
@ -26,9 +29,10 @@
<nav> <nav>
<button id="read-button">READ</button> <button id="read-button">READ</button>
<button id="save-button">SAVE</button> <button id="save-button">SAVE</button>
<span id="status">Press READ button to read PAC from settings</span>
</nav> </nav>
<div id="editor">Press READ button.</div> <div id="editor"></div>
<script src="./ace.js" type="text/javascript" charset="utf-8"></script> <script src="./vendor/ace-editor/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="./index.js"></script> <script src="./index.js" charset="utf-8"></script>
</body> </body>
</html> </html>

View File

@ -1,22 +1,35 @@
'use strict'; 'use strict';
const editor = ace.edit("editor"); const setStatusTo = (msg) => document.getElementById('status').innerHTML = msg;
const red = (text) => '<span style="color: red">' + text + '</span>';
const editor = ace.edit('editor');
editor.getSession().setOptions({ editor.getSession().setOptions({
mode: "ace/mode/javascript", mode: "ace/mode/javascript",
useSoftTabs: true useSoftTabs: true
}); });
chrome.proxy.settings.onChange.addListener( (details) => setStatusTo(red( details.levelOfControl + '!') ) );
document.querySelector('#read-button').onclick = () => { document.querySelector('#read-button').onclick = () => {
chrome.proxy.settings.get({}, (details) => { chrome.proxy.settings.get({}, (details) => {
editor.setValue( details.value.pacScript.data ); let control = details.levelOfControl;
if (control.startsWith('controlled_by_other')) {
control = red(control);
}
setStatusTo(control);
console.log(details);
const pac = details.value.pacScript;
const data = pac && pac.data || 'PAC скрипт не установлен.';
editor.setValue( data );
}); });
}; };
document.querySelector('#save-button').onclick = () => { document.querySelector('#save-button').onclick = () => {
const config = { const config = {