yomichan/ext/fg/js/frontend-api-receiver.js

58 lines
1.8 KiB
JavaScript
Raw Normal View History

/*
* Copyright (C) 2019-2020 Yomichan Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
2020-01-01 17:00:31 +00:00
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
class FrontendApiReceiver {
2019-12-12 02:59:38 +00:00
constructor(source='', handlers=new Map()) {
this._source = source;
this._handlers = handlers;
chrome.runtime.onConnect.addListener(this.onConnect.bind(this));
}
onConnect(port) {
if (port.name !== 'frontend-api-receiver') { return; }
port.onMessage.addListener(this.onMessage.bind(this, port));
}
onMessage(port, {id, action, params, target, senderId}) {
2019-12-12 02:59:38 +00:00
if (target !== this._source) { return; }
const handler = this._handlers.get(action);
if (typeof handler !== 'function') { return; }
this.sendAck(port, id, senderId);
handler(params).then(
2019-11-27 03:01:54 +00:00
(result) => {
this.sendResult(port, id, senderId, {result});
},
2019-11-27 03:01:54 +00:00
(error) => {
2019-10-08 01:04:58 +00:00
this.sendResult(port, id, senderId, {error: errorToJson(error)});
});
}
sendAck(port, id, senderId) {
port.postMessage({type: 'ack', id, senderId});
}
sendResult(port, id, senderId, data) {
port.postMessage({type: 'result', id, senderId, data});
}
}