Search code examples
javascriptangularjsnode.jsiframehtml-object

Get the value of a variable out of <iframe> or <object>


In my global html template, I have embedded an iframe, which can live-preview {{src}} (eg, src could be public/tmp/bDCZ5rynnpLaYNEuAAAj/index.html).

<iframe id="myiframe" ng-src="{{src}}"></iframe>

The index.html is a file written by my server; I have control of the code and I can modify it. index.html contains JavaScript code, it is designed such that it always has an internal variable $output.

My question is, how to get the value of $output out of the iframe and let the global html page know the value.

Does anyone know how to accomplish this?

Edit 1: I am also open to solutions where index.html could send the value to the server or create a file with the value, as long as the global template could get it later. Additionally, as I mention in comments, the purpose of iframe is to live-preview a folder of files, there are other ways to do so (eg, using <object>), does anyone know which way could let me get an internal value out?

Edit 2: I have made a plunker with iframe and a plunker with object. $output is defined by <script>var $output="Default"</script> in indexOutput.html. My goal is to get this value out.

Edit 3: I just realised that window.parent._resetter that @Roy suggested in his answer works. But one thing is, the _resetter function must be defined in the script of the html page. Does anyone know how to pass this value to my controller? Here is a plunker, and a plunker with $window.


Solution

  • You can comunicate between root and iframe with window.parent.someFunction called from the iframe. You have to create a function in root that recive a param and re setter to itself.

    function _resetter(param){
      var paramRoot = param;
    }
    


    And call this function from the iframe passing the param ouput

    window.parent._resetter(param);
    

    See https://stackoverflow.com/a/2161402/7349445