From 12f15fff5bdd51cc3418d8be9b272936d44c6d5c Mon Sep 17 00:00:00 2001 From: Stephen Sigwart Date: Thu, 30 Jul 2020 10:13:31 -0400 Subject: [PATCH] Add option to open links in new tab --- Parsedown.php | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/Parsedown.php b/Parsedown.php index ae0cbdecd..667ea80f0 100644 --- a/Parsedown.php +++ b/Parsedown.php @@ -119,6 +119,15 @@ function setStrictMode($strictMode) 'steam:', ); + protected $useTargetBlankLinks = false; + + function setTargetBlankLinks($useTargetBlankLinks) + { + $this->useTargetBlankLinks = (bool)$useTargetBlankLinks; + + return $this; + } + # # Lines # @@ -1274,6 +1283,16 @@ protected function inlineCode($Excerpt) } } + protected function updateLinkAttributes($attributes) + { + if ($this->useTargetBlankLinks) + { + $attributes['target'] = '_blank'; + $attributes['rel'] = 'noopener noreferrer'; + } + return $attributes; + } + protected function inlineEmailTag($Excerpt) { $hostnameLabel = '[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?'; @@ -1296,9 +1315,9 @@ protected function inlineEmailTag($Excerpt) 'element' => array( 'name' => 'a', 'text' => $matches[1], - 'attributes' => array( + 'attributes' => $this->updateLinkAttributes(array( 'href' => $url, - ), + )), ), ); } @@ -1395,10 +1414,10 @@ protected function inlineLink($Excerpt) 'destination' => 'elements', ), 'nonNestables' => array('Url', 'Link'), - 'attributes' => array( + 'attributes' => $this->updateLinkAttributes(array( 'href' => null, 'title' => null, - ), + )), ); $extent = 0; @@ -1547,9 +1566,9 @@ protected function inlineUrl($Excerpt) 'element' => array( 'name' => 'a', 'text' => $url, - 'attributes' => array( + 'attributes' => $this->updateLinkAttributes(array( 'href' => $url, - ), + )), ), ); @@ -1568,9 +1587,9 @@ protected function inlineUrlTag($Excerpt) 'element' => array( 'name' => 'a', 'text' => $url, - 'attributes' => array( + 'attributes' => $this->updateLinkAttributes(array( 'href' => $url, - ), + )), ), ); }