mkdocs open in new tab
mkdocs-open-in-new-tab 1.0.3
該插件在新選項卡中添加了JS代碼以打開傳出鏈接和PDF。
新標籤中鏈接的自動打開是現代網站的共同特徵。這也是可訪問性的好習慣。但是,這不是Markdown的默認行為。該插件將JavaScript代碼添加到您的網站,該代碼在新選項卡中打開外部鏈接和PDF。
看演示。
使用來自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)。
該插件向您的網站添加了JavaScript代碼,該代碼在新選項卡中打開外部鏈接和PDF。使用on_page_context掛鉤進行代碼注入。該代碼被注入頁面的<head>部分,作為open_in_new_tab.js文件的<script>依賴項。該代碼會自動添加到網站的所有頁面中。
功能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許可證的條款獲得許可的。