Pass values ​​in iframe without using GET

I have an iframe that I formally created using a URL with some vars that I passed as a GET. Is it possible to set the source page and pass variables as POST or something else? Or really, if you can somehow get the variables stored in the parent, I will also figure it out.

+6
source share
6 answers

Use window.parent from iframe.

In the parent window:

 window.passingObj = { "key" : "value" }; 

In iframe:

 alert(window.parent.passingObj["key"]); // value 
+5
source

Two helpful posts:

iframe to access parent DOM? (iframe for parent)

Call JavaScript code in an iframe from the parent page (from parent to iframe)

+1
source

If you only need access in javascript, you can use hash .

 iframe.src="http://foo.bar/#arg1=1&arg2=2"; 

and then on the page you just fetch them from location.hash.substring(1) .

this is the boilerplate code for turning these arguments into a "map":
(from my easyXDM library)

 var query = (function(input){ input = input.substring(1).split("&"); var data = {}, pair, i = input.length; while (i--) { pair = input[i].split("="); data[pair[0]] = decodeURIComponent(pair[1]); } return data; }(location.hash); query.arg1; // 1 query.arg2; // 2 
0
source

If both pages are in the same domain, you can access the variables defined on the container page from the iframe using

 parent.varName 
0
source

You can use variables and a method from the parent iframe simply by using the parent ; for example, if you have this in the parent window:

 var someObject = {key1:'value1' , key2:'value2'}; function test(key) { alert(someObject[key]); } 

you can do this in a child iframe:

 parent.test('key1'); alert(parent.someObject.key2); 

Keep in mind that this is only possible if the iframe and its parent member belong to the same domain (Same origin policy).

0
source

What are you saying for, I understand that you do not want to use url to pass your parameter.

Depending on where javascript is running, you have the following options:

  • If you did in the container window, you would do something like this

     ... var el = document.getElementById('targetFrameId'); getIframeWindow(el).someFunction('value1', 'value2', ...); // or getIframeWindow(el).someVariable = {key1:'value1', key2:'value2', ...}; ... 
  • If executed in an iframe, you will do something like this

     ... window.parent.something ... ; 

application

 function getIframeWindow(iframe_object) { var doc; if (iframe_object.contentWindow) { return iframe_object.contentWindow; } if (iframe_object.window) { return iframe_object.window; } if (!doc && iframe_object.contentDocument) { doc = iframe_object.contentDocument; } if (!doc && iframe_object.document) { doc = iframe_object.document; } if (doc && doc.defaultView) { return doc.defaultView; } if (doc && doc.parentWindow) { return doc.parentWindow; } return undefined; } 
0
source

Source: https://habr.com/ru/post/887309/


All Articles