专栏名称: 稀土掘金技术社区
掘金,一个帮助开发者成长的技术社区
目录
相关文章推荐
老刘说NLP  ·  RAG的有趣新尝试:将文本编码进MP4文件实 ... ·  2 天前  
腾讯技术工程  ·  腾讯的CMS管理系统能好用到什么程度 ·  2 天前  
腾讯技术工程  ·  腾讯Kuikly框架鸿蒙版正式开源 —— ... ·  4 天前  
51好读  ›  专栏  ›  稀土掘金技术社区

为了让 iframe 支持 keepAlive,我连夜写了个 kframe

稀土掘金技术社区  · 公众号  · 程序员  · 2025-06-02 09:00

正文

请到「今天看啥」查看全文



className?: string
style?: string
allow?: string
onLoad?: ( e: Event ) => void
onError?: ( e: string | Event ) => void
}

type IframeRect = Pick 'left' | 'top' | 'width' | 'height' > & { zIndex?: number | string }

class Iframe {
instance: HTMLIFrameElement | null = null
constructor ( private ops: IframeOptions ) {
this .init()
}
init() {
const {
src,
name = `Iframe- ${ Date .now()} ` ,
className = '' ,
style = '' ,
allow,
onLoad = () => {},
onError = () => {},
} = this .ops

this .instance = document .createElement( 'iframe' )
this .instance.name = name
this .instance.className = className
this .instance.style.cssText = style
this .instance.onload = onLoad
this .instance.onerror = onError
if (allow) this .instance.allow = allow
this .hide()
this .instance.src = src
document .body.appendChild( this .instance)
}
setElementStyle(style: Record< string , string >) {
if ( this .instance) {
Object .entries(style).forEach( ( [key, value] ) => {
this .instance!.style.setProperty(key, value)
})
}
}
hide() {
this .setElementStyle({
display: 'none' ,
position: 'absolute' ,
left: '0px' ,
top: '0px' ,
width: '0px' ,
height: '0px' ,
})
}
show(rect: IframeRect) {
this .setElementStyle({
display: 'block' ,
position: 'absolute' ,
left: rect.left + 'px' ,
top: rect.top + 'px' ,
width: rect.width + 'px' ,
height: rect.height + 'px' ,
border: '0' ,
'z-index' : String (rect.zIndex) || 'auto' ,
})
}
resize(rect: IframeRect) {
this .show(rect)
}
destroy() {
if ( this .instance) {
this .instance.onload = null
this .instance.onerror = null
this .instance.remove()
this .instance = null
}
}
}

其次是 IFrameManager 类的实现

export class IFrameManager {
static frames = new Map()
static createFame(ops: IframeOptions, rect: IframeRect) {
    const existFrame = this.frames.get(ops.uid)
    if (existFrame) {
      existFrame.destroy()
    }
    const frame = new Iframe(ops)
    this.frames.set(ops.uid, frame)
    frame.show(rect)
    return frame
  }
static showFrame(uid: string, rect: IframeRect) {
    const






请到「今天看啥」查看全文