LoginSignup
14
8

More than 3 years have passed since last update.

iframeでロードごとにiframeで今表示しているurlを取得する(iframeはオリジンサイト)[js]

Last updated at Posted at 2019-06-20

はじめに

ライブラリ未使用です。
100記事ぐらい出てきそうな内容を100回ぐらい検索しました。(言い過ぎかもしれません…)
iframeはオリジンサイトと書いているのはクロスサイトだとセキュリティー的に引っかかるからです。

セキュリティーに関して知りたい場合、
体系的に学ぶ 安全なWebアプリケーションの作り方 第2版
がおすすめです。
こんなに丁寧で情報が詰まっているのに3200円って買うしかないと思っています。

あとサイトでは、
IPAのここら辺がおすすめです。

code

sample.html
<iframe id="example1" src="https://qiita.com" width="100%" height="100%"></iframe>

sample.js
var element = document.getElementById("example1");

element.addEventListener("load", function(event) {
  let url = document.getElementById("example1").contentWindow.location.href
  console.log("現在のiframeのURLは", url);
});

codeの解説

ifarmeに『example1』というidを指定します。
idを使ってiframeを取得します。
そのiframeにloadイベントを取得するように実装します。(これでiframeロードごとに呼んでいただける)
ロードされた時に新しいurlをGetします。
以上です。

最後に

どうしてすぐにでなかったんだろう。
いや、本当は調べている時に頭が回ってなさすぎたのかもしれません…。
真相は闇の中…

参考

https://developer.mozilla.org/ja/docs/Web/Events/load
https://stackoverflow.com/questions/12069102/i-want-to-get-url-from-iframe

14
8
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
14
8