Error: Access to cross-origin frame blocked for iframe located at "http://localhost:8080" when attempting to access other iframes on the page

I am currently attempting to extract and list the names of all the iframes present on a webpage for Selenium automation.

The challenge lies in the fact that each iframe's name changes dynamically, necessitating a method to iterate through all of them.

Upon execution, I am encountering the following error:

Uncaught DOMException: Blocked a frame with origin "http://localhost:8080" from accessing a cross-origin frame.

An error arises when attempting to loop through the iframes using the following code snippet:

for (var f = 0; f < window.frames.length; f++) {
    console.log(window.frames[f].name)
}

Is there an alternative approach to retrieve the names of the iframes without encountering this issue?

Answer №1

This message indicates that...

Uncaught DOMException: Blocked a frame from accessing a cross-origin frame originating from "http://localhost:8080".

The WebDriver instance is restricted from accessing a cross-origin frame.


Cross-Origin Security Policy

Same-origin policy : This policy limits how content from one origin can interact with resources from another origin, serving as a key security measure for preventing malicious interactions between documents.


Cross-Origin Resource Sharing (CORS)

Cross-Origin Resource Sharing (CORS) : Utilizing additional HTTP headers, CORS enables a Browser Client to grant permission for the Application under Test (AUT) on one origin to access specific resources from a server on a different origin through cross-origin HTTP requests.


Example of Origin Comparison

Consider these comparisons based on the 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

Understanding the Issue

Your attempt to navigate through frames involved accessing an <iframe> with a distinct origin using JavaScript, posing a significant security risk. The same-origin policy enforced by browsers prevents scripts from interacting with frames of different origins.

For two pages to have the same origin, the protocol, port (if specified), and host must match. This concept is sometimes addressed as the "scheme/host/port tuple", requiring identical protocol, domain, hostname, and port for proper access within the same domain.

Solution

In a scenario where an AUT contains multiple frames / iframes, some may load after specific JavaScript or Ajax operations, while others may be hidden with properties like display:none; or visibility:hidden. Identifying attributes of the <iframe> and switching accordingly is recommended. Switching to an <iframe> can be achieved via:

  • Frame Name
  • Frame ID
  • Frame Index
  • WebElement

Following industry best practices, consider using WebDriverWait along with frameToBeAvailableAndSwitchToIt for efficient frame handling.

For further insights, refer to this discussion on Uncaught DOMException


References

Explore additional references:

  • A comprehensive breakdown on SecurityError: Blocked a frame with origin from accessing a cross-origin frame

  • Different approaches discussed in Is it possible to switch to an element in a frame without using driver.switchTo().frame(“frameName”) in Selenium Webdriver Java?

  • Varied strategies outlined in How can I select a html element no matter what frame it is in in selenium?

Answer №2

If you're looking to work with iframes in your code, consider the following approach:

const iframes = driver.findElements(webdriver.By.tagName("iframe"));

Loop through this list to access the attributes:

for (let i = 0; i < iframes.length; i++) {
    console.log(iframes.getAttribute("attribute name"))
}

Answer №3

If you want to extract iframe tags using selenium, you can do so by following this method:

var iframes = driver.findElements(webdriver.By.xpath("//iframe"));

Next, iterate through each element and retrieve the name attribute like this:

iframe.getAttribute('name')

Answer №4

Unconventional method:

If you're using Windows, try this:

chrome.exe --user-data-dir="" --disable-web-security

For Mac users:

open -a Google\ Chrome --args --disable-web-security --user-data-dir=""

By following these steps, you can bypass web security restrictions on Chrome.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to iterate through two arrays without disrupting the sequence of displayed elements?

I am currently working on developing a chat-bot that includes the functionality of sending and receiving voice audio. To achieve this, I have implemented two separate array states: one for rendering text messages and another for rendering audio messages. I ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

Obtain Data Grid from Website

I need to extract a table with the following columns: "Date|Open|High|Low|Close|No.of Shares|No.of trades|Total Turnover|Deliverable Qty" from the website "" Below is the code I am using: Sub Macro_BSE() Application.ScreenUpdating = False Dim File ...

Retrieve all properties associated with the current instance in the Angular 2 controller

I am looking to assign class variables with values from session storage if they exist, otherwise the variable will retain its default value initialized in ngOnInit. private getTableSessionItems = () => { var tSession = JSON.parse(sessionStorage.g ...

What is the minimum number of characters required to embed JavaScript using the HTML5 <script> element?

Is this the most efficient way to include external JavaScript on a page, now that the type attribute of the <script> tag can be omitted in HTML5? <script src="URL"></script> Is there a way to optimize this further, especially if a frame ...

Implementing CSS transitions across several elements simultaneously can enhance the user experience

There seems to be an issue with animating two elements simultaneously using max-height. The transition always occurs one after the other, with one element completing its transition before the other starts. setTimeout(function () { $(".b").css( ...

Discover the depth of a deeply nested array

I have a complex array structure that looks something like this: I am trying to determine the depth of this nested array, focusing on the element with the most deeply embedded children. let arr = [ { name: 'tiger', children: [{ ...

Angular, underscore, extracted list, arrangement

How can I use underscore or angular to sort the unique product grades and product last delivered dates before putting them into a dropdown filter? product_grades = ["", "40", "20", "30", "35", "45", "50", "60"] product_last_delivered = ["2015-07-29T00:00 ...

Locating characters within a string using JavaScript

Currently, I am enrolled in JavaScript classes and have come across a challenging question. In this scenario, the task is to create a function named countLetters. This function will take two parameters: 1) sentence - this parameter should be of type stri ...

When I expand the accordion next to it, the accordion disappears, and it also vanishes when I close that accordion

After incorporating accordions into my site, I encountered a peculiar issue (as shown in this video): when I open one accordion, the adjacent accordion also opens unexpectedly. Similarly, closing one accordion causes its neighboring accordion to mysterious ...

What steps should I follow to integrate AJAX with jQuery in order to store Summernote text in a database?

Seeking clarity on implementing Ajax with Jquery in a web app. I am new to programming with Jquery and struggling to understand existing explanations. I have a summernote text editor where users type values that I want to save in a database. Can someone pr ...

Tips on embedding an HTML page within another HTML page by utilizing a custom directive in AngularJS

I am looking to utilize custom directives in order to insert one HTML page into another. How can I achieve this? The custom directive code is as follows: (here is the .js file) fbModule.directive('fbLogin', function(){ return { ...

Updating the JSON data with a new row

I am trying to dynamically add a new row to my JSON data when the user clicks on a link. Despite not receiving any errors, I am unable to see the updated JSON in my alert message. $(document).ready( function(){ people = { "COLUMNS":["NAME","AGE"], ...

Node - ensure that each API call finishes before initiating the next one

Currently, I am encountering an issue with my POST request within the 'add-users' route. I have initialized an array named success and aim to trigger the next API call once a response is received. It seems that the problem lies in sending too ma ...

I need to prevent form submission when the submit button is clicked. How can I achieve this?

I'm currently developing a web application using ASP.net. Within the form, there is a submit button that has the following code: <input type='submit' value='submit request' onclick='btnClick();'>. The desired func ...

Do not distract the user with selenium

Currently experimenting with Selenium in C#. I'm wondering if there's a method to prevent selenium from interrupting user actions. For instance, when typing something and Selenium opens a new tab, the mouse automatically focuses on the new tab in ...

Achieving a full-height div using CSS and HTML to fill the remaining space

Here is the current layout structure I am working with: div { border: 1px solid } <div id="col_1" style="float:left;width:150px;">1</div> <div id="col_2" style="float:left;width:100px;">2</div> <div id="col_3" style="float:l ...

What is the process for including a selected-by option in a VIS network graph?

I'm trying to outline the neighboring nodes of the node that has been selected (highlightNearest). https://i.sstatic.net/lynhu.png Unfortunately, I haven't had success achieving this using JavaScript. Link to StackBlitz ...

Imagine a situation where you are faced with a web page containing a total of 10 different web links. Your task is to click on each of these links and ensure that they are opened in a

I recently encountered this question during an interview and I'm struggling to find the solution. Can you help me out? Here's the scenario: On a webpage, there is a list of 10 web links. The task is to click on each web link and open it in a new ...

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...