port document.querySelector('head') to qiankun head in micro app (#2499)

This commit is contained in:
Kuitos 2023-05-12 19:47:41 +08:00 committed by GitHub
parent bf01881c97
commit a8f5b766f8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -4,7 +4,7 @@
*/ */
import type { Freer, SandBox } from '../../../interfaces'; import type { Freer, SandBox } from '../../../interfaces';
import { isBoundedFunction, nativeDocument, nativeGlobal, isCallable } from '../../../utils'; import { isBoundedFunction, isCallable, nativeDocument, nativeGlobal } from '../../../utils';
import { getCurrentRunningApp } from '../../common'; import { getCurrentRunningApp } from '../../common';
import type { ContainerConfig } from './common'; import type { ContainerConfig } from './common';
import { import {
@ -67,24 +67,46 @@ function patchDocument(cfg: { sandbox: SandBox; speedy: boolean }) {
return true; return true;
}, },
get: (target, p, receiver) => { get: (target, p, receiver) => {
if (p === 'createElement') { switch (p) {
// Must store the original createElement function to avoid error in nested sandbox case 'createElement': {
const targetCreateElement = target.createElement; // Must store the original createElement function to avoid error in nested sandbox
return function createElement(...args: Parameters<typeof document.createElement>) { const targetCreateElement = target.createElement;
if (!nativeGlobal.__currentLockingSandbox__) { return function createElement(...args: Parameters<typeof document.createElement>) {
nativeGlobal.__currentLockingSandbox__ = sandbox.name; if (!nativeGlobal.__currentLockingSandbox__) {
} nativeGlobal.__currentLockingSandbox__ = sandbox.name;
}
const element = targetCreateElement.call(target, ...args); const element = targetCreateElement.call(target, ...args);
// only record the element which is created by the current sandbox, thus we can avoid the element created by nested sandboxes // only record the element which is created by the current sandbox, thus we can avoid the element created by nested sandboxes
if (nativeGlobal.__currentLockingSandbox__ === sandbox.name) { if (nativeGlobal.__currentLockingSandbox__ === sandbox.name) {
attachElementToProxy(element, sandbox.proxy); attachElementToProxy(element, sandbox.proxy);
delete nativeGlobal.__currentLockingSandbox__; delete nativeGlobal.__currentLockingSandbox__;
} }
return element; return element;
}; };
}
case 'querySelector': {
const targetQuerySelector = target.querySelector;
return function querySelector(...args: Parameters<typeof document.querySelector>) {
const selector = args[0];
switch (selector) {
case 'head': {
const containerConfig = proxyAttachContainerConfigMap.get(sandbox.proxy);
if (containerConfig) {
return getAppWrapperHeadElement(containerConfig.appWrapperGetter());
}
break;
}
}
return targetQuerySelector.call(target, ...args);
};
}
default:
break;
} }
const value = (<any>target)[p]; const value = (<any>target)[p];