Skip to content

Commit

Permalink
refactor: 重构拓展中的脚本加载逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
msojocs committed Sep 3, 2023
1 parent 90bd6d0 commit 664ebaf
Show file tree
Hide file tree
Showing 10 changed files with 245 additions and 83 deletions.
10 changes: 9 additions & 1 deletion CHANGELOG.MD
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
# 🌈 v1.11.4-3 / 2023-09-03

## 🐞 修复
- search: 无法搜索到外区番剧

## 🚧 其它
- extension: 重构拓展中的脚本加载逻辑

# 🌈 v1.11.4-2 / 2023-09-03

## 🐞 修复
- 用户动态无法显示
- 用户动态无法显示(该问题是由于多个实例窗口共用一个`HookXMLHttpRequest`)

## 🚧 其它
- HookXMLHttpRequest: 重构,以方便维护
Expand Down
112 changes: 66 additions & 46 deletions extensions/area_unlimit/hook.js
Original file line number Diff line number Diff line change
@@ -1,82 +1,102 @@
console.log("=====HOOK=====")

const url = new URL(location.href)
const fileName = url.pathname.substring(1).split('.')[0]

console.log("[hook]: hook.js", fileName)
const ext = chrome.extension
const URLS = {
md5: chrome.extension.getURL(`utils/md5.js`),
load: chrome.extension.getURL(`hook/load.js`),
index: chrome.extension.getURL(`hook/index.js`),
search: chrome.extension.getURL(`hook/search.js`),
player: chrome.extension.getURL(`hook/player.js`),
biliapp: chrome.extension.getURL(`hook/biliapp.js`),
commonJS: chrome.extension.getURL(`hook/common.js`),
commonCSS: chrome.extension.getURL(`hook/common.css`),
RoamingPage: chrome.extension.getURL(`hook/RoamingPage.html`),
PlayerEnhance: chrome.extension.getURL(`hook/PlayerEnhance.html`),
}
const commonJSURL = chrome.extension.getURL(`hook/common.js`);
var s = document.createElement('script');
s.src = chrome.extension.getURL(`hook/${fileName}.js`);
(document.head || document.documentElement).appendChild(s);
s.onload = function () {
s.remove();
};

// 首页搜索iframe
window.onload = () => {
console.log('search:', 'hook prepare')
const appIframe = document.getElementById('bili-app')
if (appIframe == null) {
console.warn('搜索框元素未找到!')
return
}
const appWindow = appIframe.contentWindow
console.log('search:', 'appIframe.onload')
let t = setInterval(() => {

const searchIframe = appWindow.document.querySelector(".app_search").querySelector('iframe')
if (searchIframe) {
console.log('search:', 'searchIframe')
const win = searchIframe.contentWindow
console.log(win.location.href)
const searchDocument = win.document
var commonJS = searchDocument.createElement('script');
commonJS.src = URLS.commonJS;
if (searchDocument.head || searchDocument.documentElement) {
(searchDocument.head || searchDocument.documentElement).appendChild(commonJS);
commonJS.onload = function () {
commonJS.remove();
};
clearInterval(t)
}
} else {
console.warn('search iframe not found')
}
}, 500)
// const appIframe = document.getElementById('bili-app')
// if (appIframe == null) {
// console.warn('应用主界面元素未找到!')
// return
// }
// const appWindow = appIframe.contentWindow
// console.log('search:', 'appIframe.onload')
// let t = setInterval(() => {
// console.log('try to find app_search iframe')
// const searchIframe = appWindow.document.querySelector(".app_search")?.querySelector('iframe')
// if (searchIframe) {
// console.log('search:', 'searchIframe')
// const win = searchIframe.contentWindow
// console.log(win.location.href)
// const searchDocument = win.document
// var commonJS = searchDocument.createElement('script');
// commonJS.src = URLS.commonJS;
// if (searchDocument.head || searchDocument.documentElement) {
// (searchDocument.head || searchDocument.documentElement).appendChild(commonJS);
// commonJS.onload = function () {
// commonJS.remove();
// };
// clearInterval(t)
// }
// } else {
// console.warn('search iframe not found')
// }
// }, 500)

}

var loadJS = document.createElement('script');
loadJS.src = URLS.load;
(document.head || document.documentElement).appendChild(loadJS);
loadJS.onload = function () {
loadJS.remove();
};
var commonJS = document.createElement('script');
commonJS.src = commonJSURL;
commonJS.src = URLS.commonJS;
(document.head || document.documentElement).appendChild(commonJS);
commonJS.onload = function () {
commonJS.remove();
};
var md5JS = document.createElement('script');
md5JS.src = chrome.extension.getURL(`utils/md5.js`);
md5JS.src = URLS.md5;
(document.head || document.documentElement).appendChild(md5JS);
md5JS.onload = function () {
md5JS.remove();
};

var css = document.createElement('link');
css.rel = "stylesheet"
css.href = chrome.extension.getURL(`/hook/common.css`);
(document.head || document.documentElement).appendChild(css);
// var s = document.createElement('script');
// s.src = chrome.extension.getURL(`hook/${fileName}.js`);
// (document.head || document.documentElement).appendChild(s);
// s.onload = function () {
// s.remove();
// };

// var css = document.createElement('link');
// css.rel = "stylesheet"
// css.href = URLS.commonCSS;
// (document.head || document.documentElement).appendChild(css);

// Event listener
document.addEventListener('ROAMING_getURL', function (e) {
// e.detail contains the transferred data (can be anything, ranging
// from JavaScript objects to strings).
// Do something, for example:
console.log('hook ROAMING_getURL:', e.detail);
const roamingPageURL = URLS[e.detail];
let data = null
switch (e.detail) {
case 'URLS':
data = URLS
break;
default:
data = URLS[e.detail];
break
}
document.dispatchEvent(new CustomEvent('ROAMING_sendURL', {
detail: roamingPageURL // Some variable from Gmail.
detail: data // Some variable from Gmail.
}));
});

11 changes: 11 additions & 0 deletions extensions/area_unlimit/hook/biliapp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
try {
window.hex_md5 = parent?.hex_md5
window.getHookXMLHttpRequest = parent?.getHookXMLHttpRequest
if (window.getHookXMLHttpRequest && undefined === window.XMLHttpRequest.isHooked) {
window.XMLHttpRequest = window.getHookXMLHttpRequest(window)
}
// debugger
}
catch (e) {

}
19 changes: 10 additions & 9 deletions extensions/area_unlimit/hook/common.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
console.log('[hook]: common', location.href)
// 简易GET,POST请求封装
const OriginXMLHttpRequest = XMLHttpRequest
const HTTP = {
Expand Down Expand Up @@ -711,8 +712,13 @@ const URL_HOOK = {

/*请求响应修改器1.0*/
window.getHookXMLHttpRequest = (win) => {

if (win.XMLHttpRequest.isHooked) {
return win.XMLHttpRequest
}
return class HttpRequest extends win.XMLHttpRequest {
get isHooked () {
return true
}
constructor() {
super(...arguments);
this._url = "";
Expand All @@ -739,7 +745,7 @@ window.getHookXMLHttpRequest = (win) => {
super.onreadystatechange = () => {
console.log(...arguments)
if (this.readyState === 4 && this.status === 200) {
console.log('onreadystatechange', this, super.responseType)
// console.log('onreadystatechange', this, super.responseType)
switch (super.responseType) {
case 'text':
case '': {
Expand Down Expand Up @@ -772,14 +778,9 @@ window.getHookXMLHttpRequest = (win) => {
}
break;
default:
console.warn('unsupported type:', super.responseType)
// console.warn('unsupported type:', super.responseType)
break;
}
if (this._url.includes('feed/space'))
{
console.log(this.response)
debugger
}
}
// 用于arraybuffer等
try {
Expand Down Expand Up @@ -836,7 +837,7 @@ window.getHookXMLHttpRequest = (win) => {
open() {
const arr = [...arguments];
const url = arr[1];
console.log('request for: ', ...arr)
// console.log('request for: ', ...arr)
if (url) {
const [path, params] = url.split(/\?/);
this._url = path;
Expand Down
30 changes: 6 additions & 24 deletions extensions/area_unlimit/hook/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

(() => {
console.log("===HOOK===INDEX===");
console.log("[hook]: index.js");
const HTTP_INDEX = {
get(url) {
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -348,28 +348,10 @@
// 获取App的Iframe
const appFrame = document.getElementById('bili-app')
const appWindow = appFrame.contentWindow
if(appFrame.attachEvent){
appFrame.attachEvent('onload', ()=>{
console.log("appFrame.attachEvent 'onload'")
})
}else{
appFrame.onload = ()=>{
console.log('appWindow.onload')
// console.log(window.XMLHttpRequest, targetWindow.XMLHttpRequest)
appWindow.XMLHttpRequest = window.getHookXMLHttpRequest(appWindow)
appWindow.hex_md5 = window.hex_md5
targetOnload(appWindow)
try {
const appSearchEle = appWindow.document.querySelector('.app_search')
const search = appSearchEle.querySelector('iframe')
if (!window.hex_md5) {
console.error('md5函数丢失!')
}
search.contentWindow.hex_md5 = window.hex_md5
search.contentWindow.XMLHttpRequest = window.getHookXMLHttpRequest(search.contentWindow)
}catch (e){
console.error('搜索页面md5与XMLHttpRequest初始化异常', e)
}
}
if (appWindow.document.readyState === 'complete' || appWindow.document.readyState === 'interactive') {
targetOnload(appWindow)
}
else {
console.error('页面似乎没有加载完成')
}
})();
101 changes: 101 additions & 0 deletions extensions/area_unlimit/hook/load.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
(() => {

const url = new URL(location.href)
const fileName = url.pathname.substring(1).split('.')[0]
console.log("[hook]: load.js", fileName)

const getData = (name) => {
return new Promise((resolve, reject) => {
document.addEventListener('ROAMING_sendURL', async function (e) {
// e.detail contains the transferred data (can be anything, ranging
// from JavaScript objects to strings).
// Do something, for example:
console.log('player ROAMING_sendURL: ', e.detail);
document.removeEventListener('ROAMING_sendURL', this)
if (e.detail)
resolve(e.detail)
else
reject(e)
});
document.dispatchEvent(new CustomEvent('ROAMING_getURL', {
detail: name // Some variable from Gmail.
}));
})
}

// const loadFunc = {
// index: () => {
// getFileLink('index').then(r => {
//
// })
// }
// }
// if (loadFunc[fileName]) loadFunc[fileName]()

const loadAction = async () => {
console.log('[hook]: loadAction')
const win = parent || window
if (!win.URLS) {
win.URLS = await getData('URLS')
}
console.log(fileName, 'onload', win.URLS)

if (!window.URLS)
window.URLS = win.URLS

{
if (win.URLS[fileName]) {
console.log('try to load script:', win.URLS[fileName])
const loadJS = document.createElement('script');
loadJS.src = win.URLS[fileName];
(document.head || document.documentElement).appendChild(loadJS);
loadJS.onload = function () {
loadJS.remove();
};
}
else {
console.warn('[hook]: 未找到脚本', fileName)
}
}
{
const list = document.querySelectorAll('iframe')
console.log(window)
console.log('[hook]:', `${fileName} 下的iframe数量:${list.length}`, document)
for (const item of list) {
console.log('[hook]: 给元素添加load脚本', item.id, `link->${item.src}<-`, item)
const w = item.contentWindow
const insertLoad = () => {
console.log('插入load脚本')
const loadJS = w.document.createElement('script');
loadJS.src = win.URLS.load;
(w.document.head || w.document.documentElement).appendChild(loadJS);
loadJS.onload = () => {
console.log(w.document.querySelectorAll('iframe'))
}
item.removeEventListener('load', insertLoad)
}
if (w.document.readyState === 'complete' || w.document.readyState === 'interactive') {
console.log('iframe已经加载完成')
insertLoad()
}
else {
console.log('iframe未加载完', w.document.readyState)
item.addEventListener('load', insertLoad)
}
}
}

}
let interval = setInterval(() => {
if (document.readyState === 'complete' || document.readyState === 'interactive') {
// 渲染完成
console.log('[hook]: 渲染完成,直接执行')
// loadAction().then(_ => {})
loadAction().then(_ => {})
clearInterval(interval)
}
else {
console.log('[hook]: 渲染未完成,监听执行', performance, performance.now(), performance.timing.domComplete, new Date(performance.timing.domComplete))
}
}, 500)
})()
2 changes: 1 addition & 1 deletion extensions/area_unlimit/hook/player.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ let result = ""
if(pacLink.length > 0)
result = biliBridgePc.callNativeSync('config/roamingPAC', pacLink);
if(result === 'error')localStorage.pacLink = ""
console.log("====HOOK===PLAYER====");
console.log("[hook]: player");

const sleep = (ms) => {
return new Promise((resolve, reject) => {
Expand Down
11 changes: 11 additions & 0 deletions extensions/area_unlimit/hook/search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
try {
window.hex_md5 = parent?.hex_md5
window.getHookXMLHttpRequest = parent?.getHookXMLHttpRequest
if (window.getHookXMLHttpRequest && undefined === window.XMLHttpRequest.isHooked) {
window.XMLHttpRequest = window.getHookXMLHttpRequest(window)
}
// debugger
}
catch (e) {

}
Loading

0 comments on commit 664ebaf

Please sign in to comment.