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许可证的条款获得许可的。