refactor usw content script (#1300)

* extract handlers to async functions
* limit event source to the current window
This commit is contained in:
tophf 2021-07-30 17:04:15 +03:00 committed by GitHub
parent e1b65ae21f
commit c34b054642
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,48 +2,42 @@
'use strict';
(() => {
const allowedOrigin = 'https://userstyles.world';
const sendPostMessage = message => {
if (allowedOrigin === location.origin) {
window.postMessage(message, location.origin);
}
};
const onPageLoaded = event => {
if (event.data
&& allowedOrigin === event.origin
) {
switch (event.data.type) {
case 'usw-ready': {
sendPostMessage({type: 'usw-remove-stylus-button'});
const ORIGIN = 'https://userstyles.world';
const HANDLERS = Object.assign(Object.create(null), {
async 'usw-ready'() {
send({type: 'usw-remove-stylus-button'});
if (location.pathname === '/api/oauth/style/new') {
const styleId = Number(new URLSearchParams(location.search).get('vendor_data'));
API.data.pop('usw' + styleId).then(data => {
sendPostMessage({type: 'usw-fill-new-style', data});
});
const data = await API.data.pop('usw' + styleId);
send({type: 'usw-fill-new-style', data});
}
break;
}
case 'usw-style-info-request': {
switch (event.data.requestType) {
},
async 'usw-style-info-request'(data) {
switch (data.requestType) {
case 'installed': {
API.styles.find({updateUrl: `https://userstyles.world/api/style/${event.data.styleID}.user.css`})
.then(style => {
sendPostMessage({
const updateUrl = `${ORIGIN}/api/style/${data.styleID}.user.css`;
const style = await API.styles.find({updateUrl});
send({
type: 'usw-style-info-response',
data: {installed: Boolean(style), requestType: 'installed'},
});
break;
}
}
},
});
break;
}
}
break;
}
}
}
};
window.addEventListener('message', onPageLoaded);
window.addEventListener('message', ({data, source, origin}) => {
// Some browser don't reveal `source` to extensions e.g. Firefox
if (data && (source ? source === window : origin === ORIGIN)) {
const fn = HANDLERS[data.type];
if (fn) fn(data);
}
});
function send(msg) {
window.postMessage(msg, ORIGIN);
}
})();