Last active
July 28, 2018 01:48
-
-
Save mhige/e427498980113c15d90995e2726aba19 to your computer and use it in GitHub Desktop.
Barba.jsでdocument.writeを含む外部スクリプトをDOM上に読み込む代替処理
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dispatcher (newPageReadyのところに記述) | |
Barba.Dispatcher.on('newPageReady', function(currentStatus, oldStatus, container, newPageRawHTML) { | |
// 記事内のscriptタグを取得(NodeList) | |
// querySelectorAllはDOMで細かく指定してOK | |
// 例: querySelectorAll('#content script') | |
// ↑IDがcontentのタグの中のscriptタグ | |
var scripttag = document.querySelectorAll('script'); | |
// scriptそれぞれに処理 | |
scripttag.forEach(function(script, i) { | |
// getWritten functionは下部に記載 | |
getWritten(script.src, function(html){ | |
// divタグ(class名 inrjs)を作り、その中に受け取ったHTMLを出力(HTML変換) | |
// ※inrjs は inner jsの略。適当です | |
var div = document.createElement('div'); | |
div.className = 'inrjs'; | |
div.innerHTML = html; | |
// document.writeの内容を出力 | |
script.after(div); | |
}); | |
}); | |
}); // Dispatcherここまで | |
// iframe上に一時的にwriteしてコールバックを受け取る関数 | |
// ソース元は https://teratail.com/questions/19331 | |
function getWritten(fileName, callback) { | |
var $iframe = $("<iframe hidden\/>"); | |
// iframe が DOM 上に存在しないとうまくいかないので一時的に出力する | |
$iframe.appendTo("body"); | |
var frameDocument = $iframe[0].contentWindow.document; | |
var scriptTag = "<script src=\"" + fileName + "\"><\/script>"; | |
// iframeのドキュメントを開く | |
frameDocument.open(); | |
// frame 内での window.setResult に結果受信用関数を作成する | |
$iframe[0].contentWindow.setResult = function(html) { | |
// 親フレーム上から用済みの iframe を除去する | |
$iframe.remove(); | |
// 取得した文字列には scriptTag が含まれているので削除してコールバックに渡す | |
callback(html.replace(scriptTag, "")); | |
}; | |
frameDocument.write( | |
"<div id=\"area-to-write\">" + | |
// div タグ内に scriptTag を貼る | |
scriptTag + | |
"<\/div>" + | |
"<script>" + | |
// div タグ内に出力された文字列を setResult() に渡す | |
"setResult(document.querySelector(\"#area-to-write\").innerHTML);" + | |
"<\/script>" | |
); | |
// iframeのドキュメントを閉じる | |
frameDocument.close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment