我试图列出页面中所有 iframe
的名称,以便我可以通过 Selenium 访问它们。
问题是 iframe
的名称每次都会更改,因此我需要遍历所有这些名称。
我得到:
Uncaught DOMException: Blocked a frame with origin "http://localhost:8080" from accessing a cross-origin frame.
当我尝试使用以下方法遍历它们时出错:
for (var f = 0; f < window.frames.length; f++) {
console.log(window.frames[f].name)
}
有没有办法以不同的方式获取 iframe
的名称?
最佳答案
这个错误信息...
Uncaught DOMException: Blocked a frame with origin "http://localhost:8080" from accessing a cross-origin frame.
...暗示 WebDriver 实例阻止访问跨域框架。
同源策略
Same-origin policy :同源策略限制从一个源加载的文档或脚本如何与另一个源的资源交互。它是用于隔离潜在恶意文档的关键安全机制。
跨源资源共享 (CORS)
Cross-Origin Resource Sharing (CORS) : 跨源资源共享 (CORS) 是一种机制,它使用额外的 HTTP header 告诉浏览器客户端让AUT(正在测试的应用程序) 在一个源(域)上运行,有权从不同源的服务器访问选定的资源。 Web 应用程序在请求来源(domain
、protocol
和 port
)与其自身来源不同的资源时发出跨域 HTTP 请求。
来源示例
这是与 URL http://store.company.com/dir/page.html
的来源比较示例
URL Outcome Reason
http://store.company.com/dir2/other.html Success
http://store.company.com/dir/inner/another.html Success
https://store.company.com/secure.html Failure Different protocol
http://store.company.com:81/dir/etc.html Failure Different port
http://news.company.com/dir/other.html Failure Different host
出了什么问题
当您尝试遍历 frames
时你的脚本/程序试图访问 <iframe>
使用 JavaScript 的不同来源,这将是一个巨大的安全漏洞,如果你能做到的话。如上所述,同源策略 浏览器会阻止试图访问 <iframe>
的脚本。具有不同的来源。
如果两个页面的协议(protocol)、端口(如果已指定)和主机相同,则两个页面具有相同的来源网页。您会看到它被称为 "scheme/host/port tuple"
有时(“元组”是一组三个组件,它们共同构成一个整体)。可能访问时protocol, domain, hostname and port 必须和你的同一个域一样所需的框架。
解决方案
AUT 可能包含许多 frames/iframes,其中一些可能仅在某些 JavaScript 之后加载/Ajax 已完成其中一些可能将 style 属性设置为 display:none; 或 visiblity作为隐藏。当然不需要与他们所有人互动。因此,识别 <iframe>
的属性 将是一种更好的方法并相应地切换。您可以切换到 <iframe>
通过:
-
Frame Name
-
Frame ID
-
Frame Index
-
WebElement
根据最佳实践,当您打算切换到框架时会引发 WebDriverWait对于 frameToBeAvailableAndSwitchToIt根据以下引用资料。
在这里您可以找到关于 Uncaught DOMException 的相关讨论
引用资料
一些引用资料:
在此讨论中,您将找到关于 SecurityError: Blocked a frame with origin from accessing a cross-origin frame 的详分割析。
在此讨论中,您会发现关于 Is it possible to switch to an element in a frame without using driver.switchTo().frame(“frameName”) in Selenium Webdriver Java? 的不同方法
在
A Better Approach to Switch Frames
在本次讨论的部分,您将在 How can I select a html element no matter what frame it is in in selenium? 上找到不同的方法。
关于javascript - 未捕获的 DOMException : Blocked a frame with origin "http://localhost:8080" from accessing a cross-origin frame while listing the iframes in page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51163151/