Skip to content

Commit

Permalink
feat:#85 Google插件扩展-已兼容Chrome插件
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed Sep 25, 2022
1 parent 2397a3b commit 2db93ca
Show file tree
Hide file tree
Showing 11 changed files with 591 additions and 50 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"cross-fetch": "^3.1.5",
"element-plus": "^2.2.11",
"express": "^4.18.1",
"fast-xml-parser": "^4.0.10",
"highlight.js": "^11.6.0",
"js-base64": "^3.7.2",
"js-yaml": "^4.1.0",
Expand Down
44 changes: 27 additions & 17 deletions public/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,33 @@
//
// See https://developer.chrome.com/docs/extensions/reference/events/ for additional details.
chrome.runtime.onInstalled.addListener(async () => {
console.log("Installed")
console.log("Chrome Extension Installed")
});

// function createPage() {
// // While we could have used `let url = "index.html"`, using runtime.getURL is a bit more robust as
// // it returns a full URL rather than just a path that Chrome needs to be resolved contextually at
// // runtime.
// let url = chrome.runtime.getURL("index.html");
// window.open(url)
// console.log(`Created tab`);
// }
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
switch (request.type) {
case 'fetchChromeXmlrpc':
(async () => {
const response = await fetch(request.apiUrl, request.fetchCORSParams);
const resText = await response.text()
// console.log("chrome.runtime.onMessage.addListener fetchChromeXmlrpc response:", resText)
sendResponse(resText);
})();
break;
case 'fetchChromeJson':
(async () => {
const response = await fetch(request.apiUrl, request.fetchCORSOptions);
const resJson = await response.json()
console.log("chrome.runtime.onMessage.addListener fetchChromeJson response:", resJson)
sendResponse(resJson);
})();
break;
// 你可以定义任意内容,使用sendResponse()来返回它
case 'test':
sendResponse({'msg': 'test'});
break;
}

return true; // keep the messaging channel open for sendResponse
});

// chrome.action.onClicked.addListener((tab) => {
// if (!tab.url.includes("chrome://")) {
// chrome.scripting.executeScript({
// target: {tabId: tab.id},
// function: createPage
// });
// }
// });
1 change: 1 addition & 0 deletions public/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"activeTab",
"scripting"
],
"host_permissions": [ "*://*/*" ],
"web_accessible_resources": [
{
"resources": [
Expand Down
11 changes: 11 additions & 0 deletions src/lib/chrome/ChromeUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,15 @@ export function goToPage(pageUrl: string, split?: string) {
export function isInChromeExtension() {
// @ts-ignore
return typeof chrome.runtime != "undefined";
}

/**
* 向Chrome发送消息
* @param message 消息
*/
export function sendChromeMessage(message: any) {
return new Promise((resolve) => {
// @ts-ignore
chrome.runtime.sendMessage(message, resolve)
})
}
8 changes: 5 additions & 3 deletions src/lib/constants/metaweblogMethodConstants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ const GET_USERS_BLOGS = "blogger.getUsersBlogs"
const NEW_POST = "metaWeblog.newPost"
const EDIT_POST = "metaWeblog.editPost"
const DELETE_POST = "blogger.deletePost"
const GET_CATEGORIES = "metaWeblog.getCategories"
const GET_RECENT_POSTS = "metaWeblog.getRecentPosts"
const GET_POST = "metaWeblog.getPost"
const GET_CATEGORIES = "metaWeblog.getCategories"

export const METAWEBLOG_METHOD_CONSTANTS = {
GET_USERS_BLOGS,
NEW_POST,
EDIT_POST,
DELETE_POST,
GET_CATEGORIES,
GET_POST
GET_RECENT_POSTS,
GET_POST,
GET_CATEGORIES
}
84 changes: 65 additions & 19 deletions src/lib/platform/commonblog/commonblogApi.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logUtil from "../../logUtil";
import {getWidgetId} from "../siyuan/siyuanUtil";
import {getEnv} from "../../envUtil";
import {isInChromeExtension, sendChromeMessage} from "../../chrome/ChromeUtil";

export class CommonblogApi {
constructor() {
Expand Down Expand Up @@ -51,6 +52,41 @@ export class CommonblogApi {
return await fetch(middleApiUrl, middleFetchOption);
}

/**
* 请求中转支持Chrome插件跨域
* @param apiUrl 请求地址
* @param fetchOptions 请求参数
* @param formJson 可选,发送form请求才需要
*/
private async fetchChromeCORS(apiUrl: string, fetchOptions: RequestInit, formJson?: any[]): Promise<string> {
let result
logUtil.logInfo("fetchChrome apiUrl=>")
logUtil.logInfo(apiUrl)

const fetchCORSOptions = fetchOptions
// 如果是form请求,进行转换
if (formJson) {
// 将formJson转换为formData
const form = new URLSearchParams();
formJson.forEach((item: any) => {
form.append(item.key, item.value)
})
fetchCORSOptions.body = form
}
logUtil.logInfo("fetchChrome apiUrl=>", fetchCORSOptions)

const resJson = await sendChromeMessage({
// 里面的值应该可以自定义,用于判断哪个请求之类的
type: 'fetchChromeJson',
apiUrl: apiUrl, // 需要请求的url
fetchCORSOptions: fetchCORSOptions
});
logUtil.logInfo("fetchChromeJson resJson=>", resJson)

// @ts-ignore
return resJson;
}

/**
* 同时兼容浏览器和思源宿主环境的fetch API,支持浏览器跨域
* @param apiUrl 请求地址
Expand All @@ -65,6 +101,9 @@ export class CommonblogApi {
logUtil.logWarn("当前处于挂件模式,使用electron的fetch获取数据")
// 不解析了,直接使用Node兼容调用
result = await fetch(apiUrl, fetchOptions)
} else if (isInChromeExtension()) {
logUtil.logWarn("当前处于Chrome插件中,需要模拟fetch解决CORS跨域问题")
result = await this.fetchChromeCORS(apiUrl, fetchOptions, formJson)
} else {
logUtil.logWarn("当前处于非挂件模式,已开启请求代理解决CORS跨域问题")
logUtil.logInfo("formJson=>", formJson)
Expand All @@ -75,7 +114,7 @@ export class CommonblogApi {
throw new Error("请求错误或者返回结果为空")
}

logUtil.logInfo("最终返回给前端的数据=>",result)
logUtil.logInfo("最终返回给前端的数据=>", result)

return result
}
Expand All @@ -86,7 +125,7 @@ export class CommonblogApi {
* @param fetchOptions 请求参数
* @param formJson 可选,发送form请求才需要
*/
private async fetchEntry(apiUrl: string, fetchOptions: RequestInit, formJson?: any[]): Promise<Response> {
private async fetchEntry(apiUrl: string, fetchOptions: RequestInit, formJson?: any[]): Promise<Response | string> {
const result = await this.fetchCall(apiUrl, fetchOptions, formJson)
logUtil.logInfo("请求结果,result=>")
logUtil.logInfo(result)
Expand Down Expand Up @@ -116,29 +155,36 @@ export class CommonblogApi {
throw new Error("请求异常")
}

// 解析响应体并返回响应结果
const statusCode = response.status
let resJson

if (typeof response == "string") {
console.log(response)
throw new Error("未解析")
} else {
// 解析响应体并返回响应结果
const statusCode = response.status

// const resText = await response.text()
// logUtil.logInfo("向链滴请求数据,resText=>", resText)

if (200 != statusCode) {
if (401 == statusCode) {
throw new Error("因权限不足操作已被禁止")
} else {
throw new Error("请求错误")
}
}

// const resText = await response.text()
// logUtil.logInfo("向链滴请求数据,resText=>", resText)
const widgetResult = await getWidgetId()

if (200 != statusCode) {
if (401 == statusCode) {
throw new Error("因权限不足操作已被禁止")
if (widgetResult.isInSiyuan) {
resJson = await response.json()
} else {
throw new Error("请求错误")
const corsJson = await response.json()
resJson = this.parseCORSBody(corsJson)
}
}

let resJson
const widgetResult = await getWidgetId()

if (widgetResult.isInSiyuan) {
resJson = await response.json()
} else {
const corsJson = await response.json()
resJson = this.parseCORSBody(corsJson)
}

return resJson
}
Expand Down
Loading

0 comments on commit 2db93ca

Please sign in to comment.