我正在尝试使用 bookmarlet 从从另一个域加载的 iframe 获取值。我收到 x 源错误,但我不需要在框架“之间”进行通信,我只需要从 iframe 读取数据,就像从父级读取数据一样。
我无权修改父框架或子框架。我也无法单独加载子 iframe。
我重新创建了我正在使用的结构的超级简化版本。
父页面 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>
出于此测试的目的,我试图在 iframe 中获取
innerText
的 a.button
。我创建了四个不同的 bookmarlets 来说明我的观点。
书签 1
console.log('TEST 1. TRYING TO ACCESS PARENT > H1:');
console.log(document.querySelector('h1').innerText);
结果一
TEST 1. TRYING TO ACCESS PARENT > H1:
Parent Title
书签 2
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
书签 3
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, …}
书签 4
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
我所需要的只是一个在这种情况下会返回
Child Frame Button
的解决方案。
你不能。
Bookmarklets 在顶级框架的上下文中运行。
它们与在该框架中运行的任何其他 JS 一样受到相同的跨源安全限制。