如何在MagicMirror的MMM-WebView模块中用JS移除嵌入页面元素
问题:移除MagicMirror WebView模块中嵌入网站的指定元素
我正在使用MagicMirror的MMM-WebView模块将网站嵌入魔镜,模块基础代码如下:
const WEBVIEW_ID = 'mmm-webview'; Module.register('MMM-WebView', { defaults: { url: 'https://www.google.com/', height: '640px', width: '480px', autoRefresh: false, autoRefreshInterval: 10 * 60 * 1000, loadedJS: undefined, }, start: function () { if (this.config.autoRefresh) { setInterval(() => { //Electron.session.defaultSession.clearCache(() => {}); //this.updateDom(); const webview = document.getElementById(WEBVIEW_ID); webview.reloadIgnoringCache(); }, this.config.autoRefreshInterval); } }, getDom: function () { let wrapper = document.createElement('div'); wrapper.id = 'mmm-webview-wrapper'; wrapper.innerHTML = `<webview id="${WEBVIEW_ID}" style="width: ${this.config.width}; height: ${this.config.height};" src="${this.config.url}"></webview>`; return wrapper; }, notificationReceived: function (notification, payload, sender) { if (notification == 'MODULE_DOM_CREATED') { if (this.config.loadedJS && this.config.loadedJS.length > 0) { const webview = document.getElementById(WEBVIEW_ID); if (webview) { webview.addEventListener('did-finish-load', () => { webview.executeJavaScript(this.config.loadedJS); }); } else { // TODO: Show Error } } } }, });
我想要在嵌入网站加载完成后移除其中指定ID的div元素,尝试过document.getElementById(WEBVIEW_ID).remove();和在wrapper的HTML中用jQuery等方法,都没成功,需要正确的实现方式。
解决方案
核心原理
WebView是Electron的隔离组件,主页面的JavaScript无法直接访问WebView内部的DOM,必须通过executeJavaScript()方法将代码注入到WebView的内部上下文执行。
方法1:利用模块自带的loadedJS配置(推荐)
模块已经提供了loadedJS配置项,用于在页面加载完成后执行自定义JS,直接在MagicMirror的config.js中配置即可:
{ module: "MMM-WebView", position: "top_right", // 根据你的布局调整位置 config: { url: "你的目标嵌入网址", height: "640px", width: "480px", // 替换成你要移除的元素ID loadedJS: "document.getElementById('要移除的元素ID').remove();" } }
方法2:修改模块代码内置移除逻辑
如果需要固定移除某个元素,不想每次修改配置,可以直接修改模块的notificationReceived方法,在页面加载完成后注入移除代码:
notificationReceived: function (notification, payload, sender) { if (notification == 'MODULE_DOM_CREATED') { const webview = document.getElementById(WEBVIEW_ID); if (webview) { webview.addEventListener('did-finish-load', () => { // 先执行配置中的loadedJS(如果有) if (this.config.loadedJS && this.config.loadedJS.length > 0) { webview.executeJavaScript(this.config.loadedJS); } // 注入移除指定元素的代码,替换ID为你的目标ID webview.executeJavaScript("document.getElementById('要移除的元素ID').remove();"); }); } } },
为什么之前的方法失效?
document.getElementById(WEBVIEW_ID).remove()是移除整个WebView组件本身,而非内部的目标元素;- 主页面的jQuery/JS代码运行在主上下文,无法穿透WebView的隔离环境访问内部DOM,必须用
executeJavaScript()注入代码到WebView内部执行。
内容的提问来源于stack exchange,提问作者Alex Harris
相关产品推荐
相关产品推荐

