Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a function within the context of a different window?

Tags:

javascript

dom

Let's say there's a function in the top window. For example:

function z() { alert(window.name); }

Let's also say there's an iframe in this document (same origin).

Can a function in the top window execute this function in the context of another window, such that it displays the name of the iframe and not the top window?

In other words, how is the global object bound to a function and can it be changed?

Naive attempt that doesn't work: https://jsfiddle.net/wos2o3gx/ (displays top for both invocations).

like image 367
fejesjoco Avatar asked Mar 26 '17 10:03

fejesjoco


People also ask

What is an execution context?

What is an Execution Context? Simply put, an execution context is an abstract concept of an environment where the Javascript code is evaluated and executed. Whenever any code is run in JavaScript, it's run inside an execution context.

What is meant by execution context in JavaScript?

The Execution Context contains the code that's currently running, and everything that aids in its execution. During the Execution Context run-time, the specific code gets parsed by a parser, the variables and functions are stored in memory, executable byte-code gets generated, and the code gets executed.

What is execution context and execution stack in JavaScript?

The Execution Context is an abstract environment created by JS to execute code. The Execution Stack is used to execute functions and keep track of all the Execution Context created. The Execution context is created in two stages, the creation and the execution stage.

How a function is executed in JavaScript?

The code inside a function is executed when the function is invoked. It is common to use the term "call a function" instead of "invoke a function". It is also common to say "call upon a function", "start a function", or "execute a function".


1 Answers

How is the global object bound to a function and can it be changed?

A function's global context is determined at the time the function is created, and does not change even when you make that function a property of another window context. There are dynamic alternatives, like substituting window with this, but since this isn't always set to the global object (for example in strict mode), I would suggest passing a window variable to your function instead:


Demo Snippet (JSFiddle):

function z (window) {
  window = window || self
  console.log(window.name)
}

window.name = 'w top'
z()

var iframe = document.getElementById('iframe')
iframe.contentWindow.name = 'w iframe'

z(iframe.contentWindow)
<iframe id="iframe" src="about:blank" name="w iframe">
</iframe>
like image 98
gyre Avatar answered Sep 22 '22 17:09

gyre