From 136ba0a239d9281105db8f0440d0233891b72c00 Mon Sep 17 00:00:00 2001 From: veryhappyok <18771022119@163.com> Date: Fri, 10 May 2024 17:48:00 +0800 Subject: [PATCH] feat: use fetch in chrome v3 --- package.json | 2 +- src/network/rest/restClient.ts | 4 +++- src/network/rpc/rpcClient.ts | 4 +++- src/utils.ts | 21 +++++++++++++++++++++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 49365f8..41635c8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ontology-ts-sdk", - "version": "2.0.2", + "version": "2.0.3", "description": "Comprehensive TypeScript library for the Ontology blockchain.", "main": "./lib/index.js", "types": "./lib/types/index.d.ts", diff --git a/src/network/rest/restClient.ts b/src/network/rest/restClient.ts index befc143..40a1bd7 100644 --- a/src/network/rest/restClient.ts +++ b/src/network/rest/restClient.ts @@ -22,6 +22,7 @@ import fetchAdapter from "@vespaiach/axios-fetch-adapter"; import { TEST_ONT_URL } from '../../consts'; import { Address } from '../../crypto/address'; import UrlConsts from './urlConsts'; +import { needUseFetch } from '../../utils'; /** * Wrapper class for restful api. @@ -46,7 +47,8 @@ export default class RestClient { constructor(url ?: string, useFetch?: boolean) { this.url = url || TEST_ONT_URL.REST_URL; - this.config = useFetch ? { adapter: fetchAdapter } : undefined; + const isUseFetch = useFetch || needUseFetch(); + this.config = isUseFetch ? { adapter: fetchAdapter } : undefined; if (this.url[this.url.length - 1] === '/') { this.url = this.url.substring(0, this.url.length - 1); } diff --git a/src/network/rpc/rpcClient.ts b/src/network/rpc/rpcClient.ts index 97cf3a0..71978b6 100644 --- a/src/network/rpc/rpcClient.ts +++ b/src/network/rpc/rpcClient.ts @@ -21,6 +21,7 @@ import fetchAdapter from "@vespaiach/axios-fetch-adapter"; import { TEST_ONT_URL } from '../../consts'; import { Address } from '../../crypto/address'; import { ERROR_CODE } from '../../error'; +import { needUseFetch } from '../../utils'; /** * Wrapper class for RPC apis. @@ -36,7 +37,8 @@ export default class RpcClient { constructor( url ?: string, useFetch?: boolean ) { this.url = url || TEST_ONT_URL.RPC_URL; - this.config = useFetch ? { adapter: fetchAdapter } : undefined; + const isUseFetch = useFetch || needUseFetch(); + this.config = isUseFetch ? { adapter: fetchAdapter } : undefined; } /** diff --git a/src/utils.ts b/src/utils.ts index 029b4d3..62f25e3 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -631,3 +631,24 @@ export function calcUnboundOng(balance: number, startOffset: number, endOffset: } return amount * balance; } + +// 判断是否需要使用fetch方法请求数据,在Chrome V3中只能使用fetch +export function needUseFetch() { + let useFetch = false; + try { + // 不能使用XMLHttpRequest + // @ts-ignore + const tt = new XMLHttpRequest(); + } catch (e) { + try { + // 且可以使用fetch + // @ts-ignore + const tmp = fetch; + useFetch = true; + } catch (err) { + // + } + } + + return useFetch; +}