Selenium WebDriver 如何克服同源策略

How Selenium WebDriver overcomes Same Origin Policy

Selenium WebDriver 如何克服同源策略?

Selenium RC 中存在同源策略问题

First of all “Same Origin Policy” is introduced for security reason, and it ensures that content of your site will never be accessible by a script from another site. As per the policy, any code loaded within the browser can only operate within that website’s domain.

-------------------------------------------- ---------------------------------------------- ------------------------------

它做了什么???

Same Origin policy prohibits JavaScript code from accessing elements from a domain that is different from where it was launched. Example, the HTML code in www.google.com uses a JavaScript program "testScript.js". The same origin policy will only allow testScript.js to access pages within google.com such as google.com/mail, google.com/login, or google.com/signup. However, it cannot access pages from different sites such as yahoo.com/search or fbk.com because they belong to different domains.

这就是为什么在 Selenium RC 之前,测试人员需要安装 Selenium Core(一个 JavaScript 程序)和包含被测 Web 应用程序的 Web 服务器的本地副本,以便它们属于同一个域。
-------------------------------------------- ---------------------------------------------- ----------------------------------

如何避免???

To avoid “Same Origin Policy” proxy injection method is used, in proxy injection mode the Selenium Server acts as a client configured HTTP proxy , which sits between the browser and application under test and then masks the AUT under a fictional URL

Selenium 使用 java 脚本在浏览器上驱动测试; Selenium 将自己的 js 注入到从 aut 返回的响应中。但是有一个 java 脚本安全限制 (同源策略) 允许您使用 js 修改页面的 html仅当 js 也来自与 html 相同的域时。这种安全限制非常重要,但会破坏 Selenium 的工作。这就是 Selenium 服务器发挥重要作用的地方。

在 Selenium WebDriver 之前,Selenium 是 "Javascript Task Runner"。它会将自己设置为服务器(本地),并打开指向本地 Selenium 服务器 运行 的浏览器。所以浏览器现在正在本地与 Selenium 服务器 运行 通信。

不过这是个问题,因为浏览器正在从 Selenium 获取脚本,告诉它它想从 http://websitetotest.com 获取资源。但是浏览器从 http://127.0.0.1:9000/selenium 得到了这个脚本(例如)。浏览器说“嘿这个脚本来自本地主机,现在它正在从一些外部网站请求资源。这违反了同源策略

WebDriver 出现并创建了一个代理来欺骗浏览器认为它正在与 Selenium 和 websitetotest 都是 "located" 的同一台服务器通信。 Abhishek 对此进行了简明的解释。

这可能是一个迟到的回复,但是,如果您指的是 selenium webdriver 而不是 selenium RC,那么答案是您不必担心 webdriver 的同源策略,因为每个浏览器都有自己的 webdriver.This 是 webdriver 相对于 RC 的全部优势,即没有将 selenium 核心注入浏览器,并且浏览器和 AUT.Webdriver 之间没有中间件客户端服务器,在控制浏览器自动化方面提供本机 OS 级别的支持。