-
Notifications
You must be signed in to change notification settings - Fork 0
/
backgroundHttp.js
91 lines (76 loc) · 2.21 KB
/
backgroundHttp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const baiduApi = 'https://sp1.baidu.com/5b11fzupBgM18t7jm9iCKT-xh_/sensearch/selecttext'
const googleApi = 'https://translate.google.cn/translate_a/single'
class Http {
constructor() {
this.chineseReg = /^[\u4e00-\u9fa5]+$/
}
async fetchFromBaidu(params) {
!this.baiduApi && (this.baiduApi = baiduApi)
!params._ && (params._ = Date.now())
const url = this.getCompleteUrl({ baseUrl: this.baiduApi, params })
const response = await fetch(url, {
method: 'GET'
})
return await response.json()
}
async fetchFromGoogle({ word }) {
if (!this.googleApi) this.googleApi = googleApi
let [sl, tl] = ['zh-CN', 'en']
if (!this.chineseReg.test(word.trim())) [sl, tl] = [tl, sl]
const url = this.getCompleteUrl({ baseUrl: this.googleApi, params: {
client: 'gtx',
sl,
tl,
hl: 'zh-CN',
dt: 'at',
dt: 'bd',
dt: 'ex',
dt: 'ld',
dt: 'md',
dt: 'qca',
dt: 'rw',
dt: 'rm',
dt: 'ss',
dt: 't',
ie: 'UTF-8',
oe: 'UTF-8',
source: 'btn',
ssel: '3',
tsel: '6',
kc: '0',
tk: '984327.619449',
q: word,
}})
const response = await fetch(url, {
method: 'GET'
})
return await response.json().catch(() => ({}))
}
getCompleteUrl({ baseUrl, params }) {
const url = new URL(baseUrl)
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
return url
}
async googleRequest(word) {
const googleResult = await this.fetchFromGoogle({ word }) || []
let result = 'google翻译结果解析错误'
try {
const [resultArray = []] = googleResult
result = resultArray.reduce((pre, cur) => {
return pre + (cur[0] || '')
}, "")
} catch(e) {}
return result
}
async baiduRequest(word, rect, now) {
const baiduResult = await this.fetchFromBaidu({ q: word})
// if (baiduResult.errno > 0) throw ({msg: baiduResult.error || "请求异常"})
if (baiduResult.errno > 0) return [{pre: "", cont: baiduResult.error || "请求异常"}]
let resList = baiduResult.data.result;
if (!Array.isArray(resList)) resList = [{
pre: "",
cont: resList
}]
return resList
}
}