Manipulating the content within an iframe through javascript executed from the parent document

I have a basic website located in A.html

<body>
    <p class="text">Some text</p>
</body>

There is also another site that displays A within an iframe on B.html

<body>
    <iframe id="frame" src="B.html" onload="onLoadHandler();"></iframe>
</body>

When I open file B in Google Chrome, everything appears as expected. However, when I attempt to change the color of the p element in the iframe to pink using the following line of Javascript code in B.html:

function onLoadHandler()
{
    var frameElement = document.getElementById('frame');
    var frameDocument = frameElement.contentWindow ? frameElement.contentWindow : frameElement.contentDocument.defaultView;

    var x = frameDocument.getElementsByClassName("text");
    x[0].style.backgroundColor = "pink";
}

I encounter an error at the second line:

Uncaught SecurityError: Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

This was just a test scenario, but consider a real case where we have a website www.company.com running in an iframe with www.verysecurebank.com. We want to customize the style of some buttons inside that iframe. The domains will not match in this situation.

I find it puzzling that browsers view this as cross-site scripting, while in developer tools (F12), we can manipulate the DOM of any part of the iframe without issue. We were able to turn all buttons in the iframe blue using developer tools, but Javascript in the parent HTML containing the iframe cannot achieve the same result.

Answer №1

Here are three criteria for determining if there is a cross-domain situation:

  1. Having different protocols;
  2. Using different ports;
  3. Having different domain names.

The first two criteria cannot be resolved by front-end developers. However, if the two domains share the same main domain name, the issue can be addressed by setting the document.domain to match the common main domain.

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

Navigating Assets within NodeJS Module

I'm facing a challenge with my NodeJS module that is designed to translate XML to HTML using an XSL file. The issue arises when I try to package the XSL file along with the rest of the module. Currently, the XSL file is located inside the source fold ...

Cease making commitments or declarations

I am currently working on validating an image using an API. I have implemented promises and want the execution to stop and call a function if the API check fails. Here is my code: The function for calling the promises: checkPhotos(options,formData, "fr ...

Problem with jQueryUI Sortable cancel property preventing input editing

Currently, I am utilizing jquery-3.2.1.min.js and jquery-ui.min.js version 1.12.1 The task at hand is to create a sortable list where certain elements are not sortable (specifically, other sortable lists). It is crucial that the input elements remain edit ...

Automatically reduce the size of a button without any user interaction

Is there a way to implement a menu button on my website that appears as a simple circle with an icon in the top right corner? I want it to initially load at a specific height and width, and then automatically shrink after a few moments to a different heigh ...

Error encountered in the identify() method of Microsoft Face API

While utilizing Microsoft Face API with project oxford in JavaScript, I encountered an issue when using the "identify" function resulting in an error message of "Invalid request body." client.face.identify({ faces: arrayFaceId, personGroupId: "groupId ...

Is there a method to determine if localForage/indexedDb is currently handling data operations?

Currently, I am working on a webapp that utilizes async localForage (specifically angular localForage). My goal is to alert users if they attempt to close the browser window while there are ongoing localForage operations. I have observed that some browser ...

Upon refreshing the page in Javascript, the element mysteriously vanishes without a trace

After implementing a function that should display "barProgress25" and hide "barProgress0" when a button is clicked, I encountered an issue. Upon clicking the button, the function works as intended but upon page refresh, "barProgres ...

Using the Proper 'this' Reference Without Repeating 'this' in Nested Functions

I am facing an issue in my class where I have multiple methods and properties. One of these methods contains a setTimeout() function as follows: function myClass() { this.some_property = "test"; this.PrintOnTimeout = function() { // I thou ...

Layer one div background image over another div background image

My goal is to have the Mario image displayed on top of the background seen in the screenshot below. While I've managed to get it working, I'm struggling to center the Mario image properly over the background. Additionally, I would like to elimina ...

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'</p> I have been ...

The React Testing Library encountered an error: TypeError - actImplementation function not found

Encountering a TypeError: actImplementation is not a function error while testing out this component import React from 'react'; import { StyledHeaderContainer, StyledTitle } from './styled'; export const Header = () => { return ( ...

Using a combination of ASP.NET webpage and JavaScript, a dynamic webpage with a repe

I am new to using VB and integrating JavaScript. I have a simple question, but I'm having trouble figuring it out for some reason. I am struggling to properly construct an IF-statement. Can you please help me? I have searched and googled, but have no ...

Having trouble choosing a dropdown value with ng-model; the first item keeps showing up as blank when selected

When I attempt to select a dropdown value inside an AngularJS function by setting the value to the ng-model, the dropdown initially shows a blank value selected. Below is my HTML code: <select class="pulldown" ng-model="test" ng-options="obj as obj.des ...

The blinking cursor in Google Docs is known as "kix-cursor-caret."

Although I adore Google Docs, I can't help but find the blinking cursor a bit too distracting for my liking. It seems that the latest version of Google Docs fails to comply with the operating system's setting for displaying a solid, non-blinking ...

Using three.js to control the opacity and size of points

I have returned with question number two about points. My query this time revolves around changing the opacity from 0 to 1 and back within specific pixel distances from the emitter. var particleCount = 14, particles = new THREE.Geometry(), pMaterial = new ...

Jquery Click function malfunctioning on testing environment

I'm facing a bit of challenge and could really use some assistance. I have this code snippet that functions perfectly in my test document, but once it's uploaded to the live server, everything loads correctly except for the fadeOut click function ...

JavaScript encountered an error stating that $ is undefined and has not been defined in the program

I am facing an issue while trying to submit a form in Django using AJAX. The error message displayed in the console is giving me a hard time in identifying the root cause. Despite trying several solutions, I have not been able to resolve this issue. Here i ...

The issue with fancybox links not functioning properly within ajax content

I'm looking to constantly update a specific section on my website using ajax, jquery, and php. Upon the initial page load, a javascript function is triggered to display the content of that section. Subsequently, json is utilized to check for any new ...

How come the font size and div elements combine when I drag and drop the items?

Recently, I decided to create my own drag and drop game. The game is almost complete, but there's one issue. When I try to drop the items into the designated "Drop Items Here" area, their style changes abruptly to mimic the text. For example: https: ...

Fetching data within a defined time range in Django

Currently working on creating my dashboard, the design is all set. However, I'm facing a challenge in retrieving specific data sums from my MySQL database. For instance, how can I retrieve the revenue of the last 15 days? models.py class JaGAnalytics ...