油猴脚本转Firefox扩展:如何访问并改写网页内置类与变量?
Firefox扩展实现JSC3D模型下载方案(替代油猴unsafeWindow逻辑)
问题背景
之前用油猴脚本时,靠unsafeWindow能直接改写网页的JSC3D.Scene.prototype.getChild方法,拿到scene实例后实现模型下载。但转成Firefox扩展的content script后,因为扩展的隔离机制,根本碰不到网页全局的JSC3D类,试了旧API和背景脚本也没用。
可行实现方案
核心思路是把拦截逻辑注入到网页自身的全局环境,绕过content script的隔离限制,具体步骤如下:
- 编写注入到网页的逻辑代码
把原来的拦截、下载逻辑打包成自执行函数,避免污染网页全局变量:
(function() { // 先保存原方法,避免破坏原有功能 const originalGetChild = JSC3D.Scene.prototype.getChild; // 重写getChild,保存当前scene实例到window JSC3D.Scene.prototype.getChild = function(a) { window.scene = this; return originalGetChild.call(this, a); // 保留原有逻辑正常执行 }; // 实现STL下载功能 window.downloadStl = function() { if (!window.scene) { alert('没抓到3D场景实例'); return; } // 这里放原脚本里的下载逻辑,比如导出STL const exporter = new JSC3D.STLExporter(); const stlContent = exporter.exportScene(window.scene); const blob = new Blob([stlContent], {type: 'application/sla'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'model.stl'; a.click(); URL.revokeObjectURL(url); }; // 可选:自动触发下载,或者留着让用户手动触发 // downloadStl(); })();
- 在content script中注入上述代码
通过创建script标签,把代码插入到网页的DOM中,让代码在网页全局环境执行:
// content-script.js window.addEventListener('load', () => { const injectCode = ` (function() { const originalGetChild = JSC3D.Scene.prototype.getChild; JSC3D.Scene.prototype.getChild = function(a) { window.scene = this; return originalGetChild.call(this, a); }; window.downloadStl = function() { if (!window.scene) { alert('没抓到3D场景实例'); return; } const exporter = new JSC3D.STLExporter(); const stlContent = exporter.exportScene(window.scene); const blob = new Blob([stlContent], {type: 'application/sla'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'model.stl'; a.click(); URL.revokeObjectURL(url); }; })(); `; // 创建script标签注入 const script = document.createElement('script'); script.textContent = injectCode; document.head.appendChild(script); script.remove(); // 注入后删掉标签,不占DOM空间 });
- 配置扩展manifest.json
确保content script能匹配目标网页,示例配置:
{ "manifest_version": 3, "name": "JSC3D模型下载工具", "version": "1.0", "content_scripts": [ { "matches": ["https://目标网页的域名/*"], "js": ["content-script.js"], "run_at": "document_idle" } ] }
关键说明
- 注入的代码完全运行在网页自己的全局环境,和油猴脚本用
unsafeWindow的效果一模一样,能直接访问网页的JSC3D对象。 - 如果需要从扩展的popup或者options页触发下载,可以通过
browser.runtime.sendMessage给content script发消息,再由content script触发网页里的downloadStl函数。
内容的提问来源于stack exchange,提问作者Ferinix
相关产品推荐
相关产品推荐

