In JavaScript, it is not possible to access the parent element from a different domain within an iframe

My question pertains to a bookmarklet feature I have added to my site. To utilize this feature, I have included a link titled "my bookmark" on my site. By dragging this link to my bookmarks, it can be easily accessed. When I visit another site, such as "yahoo.com," and come across content I like, I can select that content and click on "my bookmark" in my bookmarks. Doing so will open a page from my site as a child element of "yahoo.com."

To achieve this functionality, I have incorporated the following JavaScript code:

 var div = document.createElement("div");

  div.id = "instacalc_bookmarklet";

  var str = "";
  str += "<table id='instacalc_bookmarklet_table' valign='top' width='570' cellspacing='0' cellpadding='0'><tr><td width ='850' height='880'>";
  str += "<iframe frameborder='2' scrolling='yes' name='instacalc_bookmarklet_iframe' id='instacalc_bookmarklet_iframe' src='" + iframe_url + "' width='850px' height='875px' style='textalign:right; backgroundColor: white;'></iframe>";
  str += "</td><td id='closetd' onClick='toggleItem(\"instacalc_bookmarklet\");' style='background: #FFDDDD;' title='click to close window' valign='top' align='center' width='20px'>";
  str += "<a href='javascript:void(0);' style='width:100%; text-align: middle; color: #FF0000; font-family: Arial;'>x</a>";
  str += "</td></tr></table>";

  div.innerHTML = str;

  div.onkeypress = keyPressHandler;
  document.body.insertBefore(div, document.body.firstChild);

In this code snippet, there is a table tag with two td elements - one for displaying the page in an iframe and the other for the "close" button which closes the opened window within "yahoo.com."

Now, my dilemma lies in attempting to close the window by clicking a "close" button on my site. I want this action to mimic what the "close" button in the above JavaScript does, calling the "toggleItem" function.

However, I am facing the issue of being unable to access the div element within my iframe. My attempted solution looks like this:

<a href="#bookmarklet" onclick="closethis();">Close</a>


<script>

    function closethis()
    {

      id='instacalc_bookmarklet';
      var item = parent.document.getElementById(id);
      if(item){
        if ( item.style.display == "none"){
          item.style.display = "";
        }
        else{
          item.style.display = "none";
        } 
      }
    }


</script>

Upon clicking the close link, I encounter a JavaScript error stating "permission denied to get property window.document" when trying to retrieve the element by ID. Any ideas or suggestions would be greatly appreciated!

Thank you in advance.

Answer №1

Modifying this element using javascript is restricted for security purposes and cannot be altered. However, there are techniques to work around this limitation:

  • Implement a callback function to fetch data as JSONP. Note that this approach may not be suitable for all scenarios.
  • Generate a form on the webpage directing to an external domain, submit it, receive the response, and then remove the form from the DOM.

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

Enhancing Your WordPress Menu with Customized Spans

I have a WordPress menu structured like this: <div id="my_custom_class"> <ul class="my_custom_class"> <li class="page_item"><a href="#">page_item</a> <ul class='children'> <li class="page_item chil ...

The submitEvent.target cannot be converted to formdata in Vue

update I successfully created a new function based on the helpful answer provided below export function getFormDataAsJson(e) { const jsondata = {} let fd= new FormData(e.target) for (let key of fd.entries()) { jsondata[key[0]]=key[1] ...

What is the best way to incorporate a blur filter into an image?

I would like to dynamically blur my image as part of a looping process. Can anyone provide guidance on how to achieve this effect? Below is the code snippet I am currently working with: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " ...

What are the steps for creating a dropdown menu that allows for easy selection of the correct item

I am dealing with a dropdown menu as shown below. <select name="slt"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="3">Three +</option&g ...

Loop through a collection of unique identifiers for documents and establish event listeners in Firestore

Within my Vuex store, there is an action designed to retrieve a list of uids for followed users from the current user's Firestore UserDataCollection document. The action then processes each uid to extract data that will be displayed on the UI. While t ...

Utilize HTML onclick functionality with a submit button to query a JavaScript array, then showcase the specific data within the initial HTML div

I have been exploring YouTube tutorials in an attempt to learn how to effectively search for specific data entries within an array. Below is an example of a JavaScript array along with the use of console.log. JavaScript Array Example: var data = { use ...

Utilizing dropzone.js with asp.net Web Forms

Is it possible to retrieve the image properties (such as height and width) after uploading a file using dropzone.js in an .aspx application, in order to perform client-side animations? Javascript $(document).ready(function () { $(".dropzone").dropzon ...

What is the protocol for managing this exception? (specifically when a throw occurs within a callback function nested inside

Exploring the intricacies of exception handling and promises in Node.js is the focus of this query. By dissecting a simplified snippet of code, I aim to discern the similarities and differences between how exceptions are managed and promise/async functions ...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

Is it possible to exchange CSS classes for a specific group of elements using JQuery?

I have two list items listed below: <li name="luxury" class="cars luxury> <div id="featured_lux" name="featured" class="carImg_lux col2_lux "> My Luxury Car<img border="0" class="car-im ...

How to use ngModel directive in Angular to select/unselect dynamically generated checkboxes and retrieve their values

Currently, I am working with a dataset retrieved from an API and dynamically creating checkboxes in my HTML page using the DataView component from PrimeNG. My objective is to implement a feature where users can select or deselect all checkboxes with a cli ...

Real estate listing featuring unique symbols

How do I include the ' character in properties when writing my object, like this: const championsList = { Kha'Zi: '...', }; Any suggestions on how to achieve this? ...

The Power of AngularJS Directives in Harnessing jQuery DOM Event Bindings

I have developed a new directive and have some doubts about the binding syntax like element.bind("click", function(){}). Every time the link function of the directive is called, it creates a duplicate binding. What is the best Angular approach to handle th ...

What is the process for displaying the save file dialog in Safari?

I'm struggling with generating a PDF and saving it as a file in Safari using an Angular app and DocRaptor. I've tried various methods from Stack Overflow, but none seem to trigger the save file dialog. Instead, they either open the file in the cu ...

changing the visible style of a div element using JavaScript

I'm having an issue with a link on my webpage that is supposed to show or hide a <div id="po" style="display:none;">some html</div> element. The first time I click the link, the div displays properly. However, after tha ...

Troubleshooting the Netlify build error: "Encountering SyntaxError with unexpected token ;"

While deploying to Netlify, I'm encountering an error message that says: SyntaxError: Unexpected token ; Oddly enough, my master branch deploys without any issues, but every time I try to deploy my developer branch, this error pops up. Here's a ...

Retrieve the HTML content starting from the nth tag and beyond

I am currently working on a table... <table class="col-xs-12"> <thead class="testhead col-xs-12"> <tr class="col-xs-12" id="row1" style="color: white;"> <th>0</th> ...

What are the steps to display JSON data within an HTML div?

Struggling to display this JSON data within an HTML div [{ "botten": ["Crispy", "thin"] }, ] The HTML document's div has the class name box1_data. Below is my script: var crustInfo = document.getElementsByClassName("box1_data"); $.getJSON(' ...

Determining the specific button pressed using jQuery

There are two buttons present: <input type="button" name="hideAll" value="Hide Descriptions"/> <input type="button" name="showAll" value="Show Descriptions"/> Can someone guide me on how to determine which button has been clicked using jQuery ...

The supported browser is unable to import ES6 modules

Attempting to incorporate moment.js as an es6 module. The most recent version of Chrome is being utilized. Referring to the conversation here, I experimented with the src path (es6) import * as moment from './node_modules/moment/src/moment' A ...