0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

iframeから親フレームにデータを投げる(クロスオリジン対応)

Last updated at Posted at 2022-06-28

ローカルのhtmlでiframeから親フレームに処理を飛ばそうとしたところ、

test.js
window.onload = onLoad;

function onLoad() {
     var filename = window.location.pathname.match(".+/(.+?)\.[a-z]+([\?#;].*)?$")[1];
     window.parent.changeMenu(filename);
}
エラー
Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.

というエラーが発生。
クロスオリジンが発生して親の関数が実行できないらしい。

対策

データの受け渡しにparent.window.postMessage()を使用。

子フレーム
window.onload = onLoad;

function onLoad() {
   		var filename = window.location.pathname.match(".+/(.+?)\.[a-z]+([\?#;].*)?$")[1];
      	window.parent.postMessage(filename, "*");
}
親フレーム
window.addEventListener("message", function (e) {
			if($('.thisTopic').attr("id") == e.data){
		   		return;
		 	}
	    	$('.topic').removeClass('thisTopic');
	    	$('#' + e.data).addClass('thisTopic');
});

こうすることで無事に解決。
受け渡したデータはe.dataに入ってた。

参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?