このプラグインは、JSコードを追加して、新しいタブで発信リンクとPDFを開きます。
新しいタブでのリンクの自動オープニングは、最新のWebサイトの一般的な機能です。また、アクセシビリティのための良い習慣です。ただし、マークダウンのデフォルトの動作ではありません。このプラグインは、新しいタブに外部リンクとPDFを開くJavaScriptコードをWebサイトに追加します。
デモを見てください。
PYPIからのPIPを使用してプラグインをインストールします。
pip install mkdocs-open-in-new-tabプラグインをmkdocs.ymlに追加します:
plugins :
- search
- open-in-new-tab プラグインは、次の構成オプションをサポートしています。
add_icon:デフォルト:false)GoogleとGithubへのリンク。両方のリンクが新しいタブで開く必要があります。
相対リンクへの相対リンクは、同じタブで開く必要があります。
PDFへのサンプルPDFリンクは、新しいタブ(ここからPDF)で開く必要があります。
プラグインは、新しいタブに外部リンクとPDFを開くJavaScriptコードをWebサイトに追加します。コードの噴射は、 on_page_contextフックを使用して行われます。コードは、 open_in_new_tab.jsファイルの<script>依存関係として、ページの<head>セクションに挿入されます。コードは、Webサイトのすべてのページに自動的に追加されます。
関数external_new_window 、 a要素のhostnameプロパティを使用してリンクが外部であるかどうかを確認します。リンクが外部の場合、 target属性は_blankに設定され、 rel属性はnoopenerに設定されます。 noopener属性は、新しいタブがwindow.openerプロパティにアクセスするのを防ぎ、元のページに新しいタブにアクセスできないようにするために使用されます。
同じ方法で、新しいタブでPDFリンクを開くために使用されます。
このソースを見てくださいopen_in_new_tab.js:
// Description: Open external links in a new tab and PDF links in a new tab
// Based on: https://jekyllcodex.org/without-plugin/new-window-fix/
// Open external links in a new window
function external_new_window ( ) {
for ( let c = document . getElementsByTagName ( "a" ) , a = 0 ; a < c . length ; a ++ ) {
let b = c [ a ] ;
if ( b . getAttribute ( "href" ) && b . host !== location . host ) {
b . target = "_blank" ;
b . rel = "noopener" ;
}
}
}
// Open PDF links in a new window
function pdf_new_window ( ) {
if ( ! document . getElementsByTagName ) {
return false ;
}
const extensions = [ '.pdf' , '.doc' , '.docx' , '.json' , '.xls' , '.xlsx' , '.ppt' , '.pptx' , '.zip' , '.rar' , '.tar' , '.gz' , '.7z' , '.bz2' , '.xz' , '.tgz' , '.tar.gz' ] ;
let links = document . getElementsByTagName ( "a" ) ;
for ( let eleLink = 0 ; eleLink < links . length ; eleLink ++ ) {
let href = links [ eleLink ] . href . toLowerCase ( ) ; // Convert href to lowercase for case-insensitive matching
if ( extensions . some ( ext => href . endsWith ( ext ) ) ) {
links [ eleLink ] . onclick = function ( ) {
window . open ( this . href ) ;
return false ;
}
}
}
}
function apply_rules ( ) {
external_new_window ( ) ;
pdf_new_window ( ) ;
}
if ( typeof document$ !== "undefined" ) {
// Compatibility with mkdocs-material's instant loading feature
document$ . subscribe ( function ( ) {
apply_rules ( ) ;
} ) ;
} else {
// For browsers without mkdocs-material's instant loading feature
document . addEventListener ( "DOMContentLoaded" , function ( ) {
apply_rules ( ) ;
} ) ;
} open_in_new_tab.css (add_icon:trueを追加)
/*
* Materialize links that open in a new window with a right-up arrow icon
* Author: @ebouchut (https://github.com/ebouchut)
* https://github.com/JakubAndrysek/mkdocs-open-in-new-tab/issues/4
*/
a [ target = "_blank" ]:: after {
content : "↗" ;
display : inline-block;
margin-left : 0.2 em ;
width : 1 em ;
height : 1 em ;
}このプロジェクトは、MITライセンスの条件に基づいてライセンスされています。