After reducing the document.domain, the contentWindow of the iframe is met with an Access Denied error

Today, I decided to create an IFRAME dynamically using the following code snippet:

var newIframe = document.createElement("iframe");
newIframe.id = 'NewFrame';
newIframe.src = 'NewFrame.html';    
document.body.appendChild(newIframe);

After creating the IFRAME dynamically, I noticed that my document.domain was shortened from Servername.dc.com to just dc.com.

However, when I attempted to access the contentWindow, I encountered an "Access is denied" error:

document.getElementById("NewFrame").contentWindow.SomeFunction();

Note: Interestingly, everything works fine when I define the IFRAME statically in the HTML.
In an attempt to resolve this issue, I tried changing the document.domain of my IFRAME with the following line of code:

NewFrame.document.domain = dc.com;

I double-checked to ensure that both the document.domain and the domain of my IFRAME were indeed identical.

What could be causing this discrepancy? Any suggestions on what I can do next?

For context, I am using IE9 for this project.

Answer №1

Take a moment to review the correct answer provided in this article. It seems like that could be the root of your problem.

If not, consider trying out this quick workaround I came across on another post.

var frame = $('<iframe>')
.attr('id', 'myIframe')
.addClass('someClass')
.attr('src', 'javascript:(function () {' +'document.open();document.domain=\'myDomain.net\';document.close();' + '})();');
.appendTo($('#someDiv'));

Additionally, you may find some insights in this external resource link.

In response to your comment, it appears that the JavaScript function is setting the document domain rather than assigning the source, which might not be correctly executed in Internet Explorer.

For further examples and explanations, refer to this source.

You can try implementing something like the following...

var wrapUpIframe = document.createElement("iframe");
wrapUpIframe.id = 'WrapUpDialog3';    
wrapUpIframe.src = setSrc();
document.body.appendChild(wrapUpIframe);

function setSrc(){
    document.open();
    document.domain='dc.com';
    document.close();
    return 'WrapUpDialog.html';
}

Adjust as needed to ensure the URL for the iframe is returned after setting the document domain. This approach may work for your situation based on my observations.

While my experience with a similar issue may not directly solve your problem, adjusting the function that sets the document domain helped me bypass the access denied error.

To further align domains, you can include the following script in your main document.

<script type="text/javascript">
    document.domain = 'dc.com';
</script>

I also recommend checking this informative resource for an explanation on explicitly setting the document domain, which proved beneficial in my past experiences. Notably, consider this quote...

Explicitly setting the value indicates intent to "cooperate" with a script on another subdomain (under the same parent domain).

Lastly, if timing is a concern, you could address it using code like this snippet that ensures the iframe is loaded before accessing contentWindow.

var iframe = document.createElement("iframe");
iframe.src = "WrapUpDialog.html";

if (iframe.attachEvent){
    iframe.attachEvent("onload", function(){
        alert("Local iframe is now loaded.");
    });
} else {
    iframe.onload = function(){
        alert("Local iframe is now loaded.");
    };
}

document.body.appendChild(iframe);

var iframeWindow = iframe.contentWindow || iframe.contentDocument.parentWindow;

Answer №2

Are you experiencing issues serving your files? Have you noticed the presence of file:/// in your URL bar? If so, consider utilizing a web server for hosting.

When attempting to access your code via file:///, Google Chrome may display an access denied error. However, serving the code from a local webserver (such as http://localhost/) resolves this issue and allows it to function properly.

Answer №3

If you haven't accepted any of the provided answers yet, it's likely that you still have the problem at hand.

To address this issue, make sure to explicitly set document.domain in both HTML pages involved, not just one. As suggested by @Vic, add the following JavaScript code to the HTML containing the iframe:

document.domain = 'dc.com';

Your code should then appear as follows:

document.domain = 'dc.com';
var wrapUpIframe = document.createElement("iframe");
wrapUpIframe.id = 'WrapUpDialog3';
wrapUpIframe.src = 'WrapUpDialog.html';    
document.body.appendChild(wrapUpIframe);

Furthermore, in the WrapUpDialog.html itself (not in the main page to maintain security), ensure to also set document.domain:

document.domain = dc.com;

Keep in mind that the line below will not function as intended:

WrapUpDialog3.document.domain = 'dc.com';

This is because WrapUpDialog.html must authorize its "parent" page to execute its JavaScript code.

You can find more information on this topic here: What does document.domain = document.domain do?.

Lastly, test your code across different browsers such as IE9, Firefox, and Google Chrome to detect any browser-specific issues that may arise.

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

Tips for resolving the "Unexpected reserved word" error during the installation of Laravel Jetstream

I have been following the steps outlined on to set up Laravel Jetstream. Upon running artisan jetstream:install, I selected Livewire support, API support, email verification, and PHPUnit support for installation. Next, I executed npm install as per the ...

The publish-subscribe feature appears to be ineffective

Recently starting with meteor, I learned about the importance of removing autopublish. So, I decided to publish and subscribe to a collection in order to retrieve two different sets of values. Here is the code on my meteor side: Meteor.publish('chann ...

Error in Typescript: 'SyncClient' not found in Twilio

While working on my Ionic app, I encountered an issue every time I attempted to use the twilio-chat library in my project through npm install. The error consistently appeared in the .d.ts files. Here is how I imported it in my provider : import { Client ...

Prevent tab key focus in jQuery UI autocomplete

Sharing my own answer here: Here is the HTML code I am working with: <select id="genre-select"> <option value="-1">Please select</option> <option value="1">One</option> <option value="2">Two ...

Implementing a function to specify size limits

As a newcomer to the world of JavaScript, I am facing a particular challenge. My goal is to add a conditional statement in my code that will only execute on screen sizes larger than 768px. $(window).on('scroll', function () { if ($(window ...

Exploring the possibilities of combining DOM and Express in web development

app.post('/result.html',function(req,res){ var num1 = req.body.Num1 ; var num2 = req.body.Num2 ; var operator = req.body.Operator ; var result =0 ; switch (operator) { case '+': result = Number(num1)+Number(num2) ; ...

Use the clientID property of the controlname element within JavaScript to access the element using the getElementById method with only

I have a customized compound control that I need to deactivate. This control includes a text field and a calendar component. I want to disable both the image and the text field. Here is how it is identified on the page. The control's name is "datepic ...

history.js - failure to save the first page in browsing history

I have implemented the history.js library to enable backward and forward browser navigation on an AJAX products page triggered by clicking on product categories. While I have managed to get this functionality working smoothly, I am facing a particular iss ...

Customizing material-ui styles within a nested component

I am looking to modify the position of the expandIcon in an ExpansionPanel by changing the right attribute: <ExpansionPanel> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}&g ...

Establish a connection between the Discord Bot and a different channel

I need help with my Discord bot that should redirect someone to a different channel when they mention certain trigger word(s). I feel like there might be a missing line or two of code that I need to add to make it work properly. bot.on("message", messag ...

Retrieve the text label from the parent option group

Below is the HTML code snippet: <select id="categoryg"> <optgroup label="Main" value="binding"> <optgroup label="Sub" value="binding"> <option value="46&quo ...

Create a dynamic animation effect for the placeholder in an input field that triggers when the user starts typing

Have you ever come across interactive demos like this one? I've noticed that most examples involve creating a new element. parent().append("<span>" + $input.attr('placeholder') + "</span>"); Is there a way to make the placehol ...

Dealing with redirect issues in a React-Material menu: A guide to troubleshooting and

When working with my menu, I face a variety of issues. First and foremost, within the initial RETURN section, there is a TREEITEM with a LISTITEM and a LISTITETEXT. I have included an OnClick event in the LISTITETEXT so that if the menu's id matches ...

jQuery's show/hide function exhibiting inconsistencies when checking or unchecking

I have implemented a feature on my webpage where there is a field for previous surgeries with certain elements. The goal is to display the previous surgery elements only if the "previous surgery" checkbox is checked. Below is a snippet of the code I'm ...

Button Click Does Not Trigger Bootstrap Modal Display

This is a sample Bootstrap document that includes JS and CSS files to display a list properly in Bootstrap. However, the Modal does not appear when clicking on Launch demo modal. No JavaScript errors are displayed in the Console. Can you help troubleshoot ...

How to Retrieve Checkbox Values from Multiple Rows Using JavaScript

I have a variety of module rows that allow users to manage access rights by selecting specific options. My goal now is to extract the checked boxes from these checkboxes with the name "config{{$field->id}}". Below is the current functioning code. HTM ...

Node.js frequently returns null with its url methods

I'm having some trouble getting node.js to display the HTTP request properties in the browser. I've tried printing the properties of the request URL, but they either show up as null or don't display at all. Below is the code for the server ( ...

Combine the elements by using a computed item mapping

I want to verify that all elements in an array are of the type Item. However, once I implement this, the splice method stops functioning properly. This is my current approach: computedItems: { get() { //return this.modelValue; retu ...

Remove browser data in PhoneGap / Prevent PhoneGap from utilizing cookies

Currently, I am in the process of creating a login system for my mobile application. After logging in to my server, it sends back a JSESSIONID that I can utilize for further authentication. The issue I am encountering is that PhoneGap is automatically st ...

Utilizing hyperlinks within NicEdit content and managing events with jQuery

I am using nicEdit, a rich editor, on my website to insert hyperlinks into the content. While I can successfully add hyperlinks using the setContent() method after initializing nicEdit, I am facing issues with handling click events for hyperlinks that have ...