如何用Bookmarklet获取跨域iframe的innerText?解决同源错误
跨域iframe数据读取解决方案需求
问题背景
需通过Bookmarklet读取其他域名iframe内的数据,遭遇跨源错误。无法修改父页面或子iframe,也不能单独加载子iframe,目标是获取iframe内a.button元素的innerText(预期值:Child Frame Button)。
页面结构
父页面(url1.com/parent.html)
<body> <h1>Parent Title</h1> <iframe src="url2.com/child.html" id="xoFrame"></iframe> </body>
子iframe(url2.com/child.html)
<body> <h1>Child Iframe Title</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus congue est vitae mauris pulvinar hendrerit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p> <a class="button" href="#">Child Frame Button</a> <footer>© Footer Text 2048</footer> </body>
现有尝试及结果
Chrome跨域禁用命令(Chrome 109中无效)
chrome.exe --disable-web-security --disable-gpu --disable-features=IsolateOrigins,site-per-process --user-data-dir="C://chrome-dev"
四个Bookmarklet测试
Bookmarklet 1(访问父页面元素)
console.log('TEST 1. TRYING TO ACCESS PARENT > H1:'); console.log(document.querySelector('h1').innerText);
结果1:
TEST 1. TRYING TO ACCESS PARENT > H1: Parent Title
Bookmarklet 2(直接查找子iframe元素)
console.log('TEST 2. TRYING TO ACCESS CHILD IFRAME > A.BUTTON DIRECTLY'); console.log(document.querySelector('a.button').innerText);
结果2:
TEST 2. TRYING TO ACCESS CHILD IFRAME > A.BUTTON DIRECTLY Uncaught TypeError: Cannot read properties of null (reading 'innerText') at <anonymous>:1:132 at <anonymous>:1:145
Bookmarklet 3(访问iframe的contentWindow)
console.log('TEST 3. TRYING TO ACCESS IFRAME > CONTENTWINDOW'); console.log(document.getElementById('xoFrame').contentWindow);
结果3:
TEST 3. TRYING TO ACCESS IFRAME > CONTENTWINDOW global {window: global, self: global, location: {…}, closed: false, frames: global, …}
Bookmarklet 4(访问iframe的contentWindow.document)
console.log('TEST 4. TRYING TO ACCESS IFRAME > CONTENTWINDOW > DOCUMENT'); console.log(document.getElementById('xoFrame').contentWindow.document);
结果4:
TEST 4. TRYING TO ACCESS IFRAME > CONTENTWINDOW > DOCUMENT Uncaught DOMException: Blocked a frame with origin "url1.com" from accessing a cross-origin frame. at <anonymous>:1:147 at <anonymous>:1:159
解决方案
修正Chrome跨域禁用启动命令(适配Chrome 109+)
Chrome 109之后新增了额外的隔离机制,需要补充禁用参数,启动命令调整为:
chrome.exe --disable-web-security --disable-gpu --disable-features=IsolateOrigins,site-per-process,CrossSiteDocumentBlockingIfIsolating --user-data-dir="C:\chrome-dev"
注意:
user-data-dir必须指定一个全新的目录,避免和默认Chrome用户数据冲突。
可用的Bookmarklet
当Chrome以上述命令启动后,使用以下Bookmarklet即可读取目标元素的innerText:
(() => { const iframe = document.getElementById('xoFrame'); if (iframe && iframe.contentWindow) { const button = iframe.contentWindow.document.querySelector('a.button'); if (button) { console.log(button.innerText); alert(button.innerText); // 可选:直接弹窗显示结果 } else { console.log('目标按钮未找到'); } } else { console.log('无法访问iframe'); } })();
内容的提问来源于stack exchange,提问作者spimcom
相关产品推荐
相关产品推荐

