code optimize

This commit is contained in:
2020-01-15 15:21:17 +08:00
parent da7ae057f4
commit 3338f78d91
5 changed files with 43 additions and 38 deletions

View File

@ -1,4 +1,4 @@
import { ACTION_GOTO_URL, ACTION_EXTRACT, ACTION_PING as ACTION_PING, ACTION_QUERY_URL, ACTION_SCROLL_BOTTOM } from "../common";
import { Actions, Request } from "../common";
import { sendMessage } from "./messaging";
/**
@ -10,8 +10,8 @@ import { sendMessage } from "./messaging";
export function redirectTab(tab: chrome.tabs.Tab, url: string) {
return queryUrl(tab).then(u => {
if (url !== u) {
let req = {
action: ACTION_GOTO_URL,
let req: Request = {
action: Actions.GOTO_URL,
url: url
}
let checker = async (u, err, tryCount): Promise<string> => {
@ -43,7 +43,7 @@ export function redirectTab(tab: chrome.tabs.Tab, url: string) {
*/
export function extractTabData(tab, itemsSelector, fieldSelectors) {
let req = {
action: ACTION_EXTRACT,
action: Actions.EXTRACT,
itemsSelector: itemsSelector,
fieldSelectors: fieldSelectors
}
@ -67,7 +67,7 @@ export function extractTabData(tab, itemsSelector, fieldSelectors) {
*/
export async function ping(tab, count = 1) {
let req = {
action: ACTION_PING
action: Actions.PING
}
let checker = (r: string, e, c) => r == "pong" ? r : undefined;
let pong = await sendMessage<string>(tab, req, 'Check tab availability...', checker, 1000, count).catch(() => { });
@ -81,7 +81,7 @@ export async function ping(tab, count = 1) {
*/
export function queryUrl(tab: chrome.tabs.Tab) {
let req = {
action: ACTION_QUERY_URL
action: Actions.QUERY_URL
}
return sendMessage<string>(tab, req);
}
@ -94,7 +94,7 @@ export function queryUrl(tab: chrome.tabs.Tab) {
*/
export function scrollToBottom(tab: chrome.tabs.Tab) {
let req = {
action: ACTION_SCROLL_BOTTOM
action: Actions.SCROLL_BOTTOM
}
return sendMessage(tab, req, 'Scroll to page bottom...');
}

View File

@ -1,4 +1,4 @@
import { EXT_NAME, ACTION_UPLOAD_STATE } from "../common";
import { Request, Actions } from "../common";
import { getTabByID } from "./actions";
import { caches, logger } from "./common";
@ -78,14 +78,11 @@ export function sendMessage<T>(
});
}
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (!request.action || !request.action.startsWith(EXT_NAME)) {
return;
}
chrome.runtime.onMessage.addListener(function (request: Request, sender, sendResponse) {
switch (request.action) {
case ACTION_UPLOAD_STATE:
case Actions.UPLOAD_STATE:
sendResponse('recieved!');
caches.setState(request.name, request.state)
caches.setState(request.fileName, request.state)
break;
default:
sendResponse("Request not supported.");