Tips for invoking a JavaScript function within an iframe

I'm looking to add an iframe to my HTML document, but I also need to pass a variable from a JavaScript function that is located on the same page (which retrieves cookie values).

<script type=text/JavaScript>
var generateLinkerUrl = function(url){ etc...
  </script>
<body>

<iframe src=
var newUrl =
generateLinkerUrl("http://blog.domain.com/mypage.php") // url of the iframe </iframe>`  

Is the way I am calling the JavaScript function inside the 'script' tag correct or do I need to add something else?

Thank you very much.

Answer №1

It's not possible to insert a JavaScript function inside an iframe tag as it may seem like you are trying to do. The purpose behind your attempt is not clearly understood, but here is some guidance:

If the iframe and host document are on different domains, direct JavaScript access between them will be blocked by the browser, except for using window.postMessage() for communication.

However, if the iframe and host document are on the same domain, you can access the contents of the iframe like this:

// Get the DOM element of the iframe from the host document
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

From there, you can access the window object to interact with global JavaScript variables or functions.

To call a function within an iframe on the same domain, follow these steps:

var iframe = document.getElementById("myIframe");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var iframeWindow = iframeDocument.window;

// Call the function in the iframe
iframeWindow.funcIniFrame("xxx");

If your goal is to have an iframe with a dynamically generated .src attribute from the host document, you can achieve that without any domain restrictions by doing the following:

<iframe id="myIFrame"></iframe>

<script>
document.getElementById("myIFrame").src = generateLinkerUrl("http://blog.domain.com/mypage.php");
</script>

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

Preventing Vue.js from triggering watch on initial load

I need to implement a feature where a button is initially disabled and only becomes enabled when the input value is changed. To achieve this, I am using a boolean flag that is set to true by default and turns false only when the input changes. The v-model ...

Automatically close the multiselect dropdown when the user interacts outside of it (varied scenario)

For those interested, check out this jsfiddle link: http://jsfiddle.net/jaredwilli/vUSPu/ This specific code snippet focuses on creating a multi-select dropdown feature. When a user chooses options from the dropdown and then clicks outside of the menu are ...

How can I disable auto-fill for password input fields? Setting autocomplete="off" doesn't seem to be working

Hey there, I'm having some trouble with the autocomplete feature in Google Chrome. Can anyone suggest an alternative way to disable autocomplete for password fields? By the way, my project is using Vue.js. ...

It is likely that the variable is out of scope and is undefined

I have a piece of code that retrieves the description of a word in JSON format from website, which is provided by the user in the request JSON body. The issue I'm facing is that I am unable to send back the 'desc' variable in the res.send ...

Encountering a Module node browserify issue

I recently attempted to utilize the Dyson module node from https://github.com/webpro/dyson#installation. However, upon executing the 'dyson' command, I encountered the following error in my terminal. $ dyson Prueba/ module.js:491 throw err ...

Customizing Marker Clusters with ui-leaflet: A guide on changing marker cluster colors

I'm trying to customize the markerCluster color in a non-default way. I've been exploring the API and it looks like the recommendation is to modify a divIcon after creation, possibly like this: var markers = L.markerClusterGroup({ iconCreateFunc ...

Can AJAX function properly when the server-side code is hosted on a separate domain?

After opening Firefox's scratchpad and inputting the following code... function ajaxRequest() { var xmlhttp; var domainName = location.host; var url = 'http://leke.dyndns.org/cgi/dn2ipa/resolve-dns.py?domainName='; url = url + domainName + ...

I am looking to create a route with parameters in Next.js, as well as without any parameters

I am working on a NEXTJS project and utilizing SSR for data fetching. However, I am trying to implement the following scenario: When users land on the "/" route, they should be presented with a random product detail page. But if they search for a specific ...

I am encountering an error that states: UnhandledPromiseRejectionWarning: TypeError: Unable to retrieve the property 'buffer' as it is undefined

I am facing an issue with my code where I am unable to upload new files to my website. Can someone help me understand what might be causing this problem? const multer = require("multer"); const upload = multer({ storage: multer.memoryStorage() ...

Integrate an item into the request body utilizing the $.load() function in jQuery

Currently, I am using a POST request via jQuery's $.load function to retrieve data to display in a window. This is what I am currently doing: var testObject = { thing1: 'data1', thing2: 'data2', thing3: &a ...

Utilizing React Recharts to create personalized tooltips

In my current project, I am looking to create a custom tooltip to replace the default one in recharts. The default tooltip that I want to change is shown below: https://i.stack.imgur.com/TjTiL.png I would like the new custom tooltip to look like this: ...

Exploring textboxes with jQuery loops

Is there a way to clear all these textboxes by iterating through them using Jquery? <div class="col-md-4" id="RegexInsert"> <h4>New Regex Pattern</h4> <form role="form"> <div class="form-group"> &l ...

Placeholder variable not specified in radio buttons

I am currently facing challenges applying validations to radio buttons in Angular. Normally, I create a #templateRefVariable on the input for other input types, which allows me to access the NgControl and use properties like touched. My goal is to set the ...

Repeated information in HTML tables

I am currently working with two HTML tables and two sets of JSON data. Initially, I load one table with the tableData which has a default quantity of 0. In my HTML form, there are three buttons - save, load draft, and edit. Upon clicking on load draft, I p ...

Is it possible to compare two charts in Chart.js in a way that avoids the issue of small values appearing as large as big values?

I am currently working on a production tracking page that features multiple charts. I want to avoid inconsistencies in tracking at first glance. Is there a way to achieve this using chart.js? If not, what would be the best approach to address this issue? ...

Experiencing difficulty in connecting with the service providers

What's the process for obtaining these providers? I recently followed the JavaScript Mastery tutorial step by step, however, I encountered an issue with the useEffect hook to fetch the providers (I even tried using alert to check, but it keeps showin ...

The performance of the React create app proxy agent in the package.json file seems to be sluggish,

In our react application (created as create-react-app), we have a proxy defined in the `package.json`. This proxy is used between the front-end (webpack) and back-end (express) during development, as outlined here. The section of the `package.json` where t ...

What is the best way to find the most commonly used category for a product in a MongoDB collection?

I've been diving into MongoDB and encountered a challenge with my current task. I'm trying to figure out how to determine the most frequently used category in a collection. According to this JSON, the most used category is CIES. My goal is to dis ...

Creating an object instance in Angular 2 using TypeScript

Looking for guidance on creating a new instance in TypeScript. I seem to have everything set up correctly, but encountering an issue. export class User implements IUser { public id: number; public username: string; public firstname: string; ...

The content of xmlhttp.responseText is not being displayed in the innerHTML

As part of my ongoing effort to enhance my understanding of Ajax for work purposes, I have been following the W3Schools tutorial and experimenting with my Apache2 server. In this process, I have placed a file named ajax_info.txt on the server (in /var/www ...