Is there a way to create a link in Markdown that opens in a new window? If not, what syntax do you recommend to do this? I'll add it to the markdown compiler I use. I think it should be an option.
As far as the Markdown syntax is concerned, if you want to get that detailed, you'll just have to use HTML.
Hello, world!
Most Markdown engines I've seen allow plain old HTML, just for situations like this where a generic text markup system just won't cut it. (The StackOverflow engine, for example.) They then run the entire output through an HTML whitelist filter, regardless, since even a Markdown-only document can easily contain XSS attacks. As such, if you or your users want to create _blank links, then they probably still can.
If that's a feature you're going to be using often, it might make sense to create your own syntax, but it's generally not a vital feature. If I want to launch that link in a new window, I'll ctrl-click it myself, thanks.
Kramdown supports it. It's compatible with standard Markdown syntax, but has many extensions, too. You would use it like this:
[link](url){:target="_blank"}
I don't think there is a markdown feature, although there may be other options available if you want to open links which point outside your own site automatically with JavaScript.
Array.from(javascript.links)
.filter(link => link.hostname != window.location.hostname)
.forEach(link => link.target = '_blank');
jsFiddle.
If you're using jQuery:
$(document.links).filter(function() {
return this.hostname != window.location.hostname;
}).attr('target', '_blank');
jsFiddle.
With Markdown v2.5.2, you can use this:
[link](URL){:target="_blank"}
So, it isn't quite true that you cannot add link attributes to a Markdown URL. To add attributes, check with the underlying markdown parser being used and what their extensions are.
In particular, pandoc has an extension to enable link_attributes, which allow markup in the link. e.g.
[Hello, world!](http://example.com/){target="_blank"}
For those coming from R (e.g. using rmarkdown, bookdown, blogdown and so on), this is the syntax you want.
For those not using R, you may need to enable the extension in the call to pandoc with +link_attributes
Note: This is different than the kramdown parser's support, which is one the accepted answers above. In particular, note that kramdown differs from pandoc since it requires a colon -- : -- at the start of the curly brackets -- {}, e.g.
[link](http://example.com){:hreflang="de"}
In particular:
# Pandoc
{ attribute1="value1" attribute2="value2"}
# Kramdown
{: attribute1="value1" attribute2="value2"}
^
^ Colon
One global solution is to put <base target="_blank">
into your page's <head> element. That effectively adds a default target to every anchor element. I use markdown to create content on my Wordpress-based web site, and my theme customizer will let me inject that code into the top of every page. If your theme doesn't do that, there's a plug-in
Not a direct answer, but may help some people ending up here.
If you are using GatsbyJS there is a plugin that automatically adds target="_blank" to external links in your markdown.
It's called gatsby-remark-external-links and is used like so:
yarn add gatsby-remark-external-links
plugins: [
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [{
resolve: "gatsby-remark-external-links",
options: {
target: "_blank",
rel: "noopener noreferrer"
}
}]
}
},
It also takes care of the rel="noopener noreferrer".
Reference the docs if you need more options.
For ghost markdown use:
[Google](https://google.com" target="_blank)
Found it here:
https://cmatskas.com/open-external-links-in-a-new-window-ghost/
I'm using Grav CMS and this works perfectly:
Body/Content:
Some text[1]
Body/Reference:
[1]: http://somelink.com/?target=_blank
Just make sure that the target attribute is passed first, if there are additional attributes in the link, copy/paste them to the end of the reference URL.
Also work as direct link:
[Go to this page](http://somelink.com/?target=_blank)
You can do this via native javascript code like so:
var pattern = /a href=/g;
var sanitizedMarkDownText = rawMarkDownText.replace(pattern,"a target='_blank' href=");
JSFiddle Code
In my project I'm doing this and it works fine:
[Link](https://example.org/ "title" target="_blank")
Link
But not all parsers let you do that.
There's no easy way to do it, and like #alex has noted you'll need to use JavaScript. His answer is the best solution but in order to optimize it, you might want to filter only to the post-content links.
<script>
var links = document.querySelectorAll( '.post-content a' );
for (var i = 0, length = links.length; i < length; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
</script>
The code is compatible with IE8+ and you can add it to the bottom of your page. Note that you'll need to change the ".post-content a" to the class that you're using for your posts.
As seen here: http://blog.hubii.com/target-_blank-for-links-on-ghost/
If someone is looking for a global rmarkdown (pandoc) solution.
Using Pandoc Lua Filter
You could write your own Pandoc Lua Filter which adds target="_blank" to all links:
Write a Pandoc Lua Filter, name it for example links.lua
function Link(element)
if
string.sub(element.target, 1, 1) ~= "#"
then
element.attributes.target = "_blank"
end
return element
end
Then update your _output.yml
bookdown::gitbook:
pandoc_args:
- --lua-filter=links.lua
Inject <base target="_blank"> in Header
An alternative solution would be to inject <base target="_blank"> in the HTML head section using the includes option:
Create a new HTML file, name it for example links.html
<base target="_blank">
Then update your _output.yml
bookdown::gitbook:
includes:
in_header: links.html
Note: This solution may also open new tabs for hash (#) pointers/URLs. I have not tested this solution with such URLs.
In Laravel I solved it this way:
$post->text= Str::replace('<a ', '<a target="_blank"', $post->text);
Not works for a specific link. Edit all links in the Markdown text. (In my case it's fine)
I ran into this problem when trying to implement markdown using PHP.
Since the user generated links created with markdown need to open in a new tab but site links need to stay in tab I changed markdown to only generate links that open in a new tab. So not all links on the page link out, just the ones that use markdown.
In markdown I changed all the link output to be <a target='_blank' href="..."> which was easy enough using find/replace.
I do not agree that it's a better user experience to stay within one browser tab. If you want people to stay on your site, or come back to finish reading that article, send them off in a new tab.
Building on #davidmorrow's answer, throw this javascript into your site and turn just external links into links with target=_blank:
<script type="text/javascript" charset="utf-8">
// Creating custom :external selector
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/)
&& (obj.hostname != location.hostname);
};
$(function(){
// Add 'external' CSS class to all external links
$('a:external').addClass('external');
// turn target into target=_blank for elements w external class
$(".external").attr('target','_blank');
})
</script>
You can add any attributes using {[attr]="[prop]"}
For example [Google] (http://www.google.com){target="_blank"}
For completed alex answered (Dec 13 '10)
A more smart injection target could be done with this code :
/*
* For all links in the current page...
*/
$(document.links).filter(function() {
/*
* ...keep them without `target` already setted...
*/
return !this.target;
}).filter(function() {
/*
* ...and keep them are not on current domain...
*/
return this.hostname !== window.location.hostname ||
/*
* ...or are not a web file (.pdf, .jpg, .png, .js, .mp4, etc.).
*/
/\.(?!html?|php3?|aspx?)([a-z]{0,3}|[a-zt]{0,4})$/.test(this.pathname);
/*
* For all link kept, add the `target="_blank"` attribute.
*/
}).attr('target', '_blank');
You could change the regexp exceptions with adding more extension in (?!html?|php3?|aspx?) group construct (understand this regexp here: https://regex101.com/r/sE6gT9/3).
and for a without jQuery version, check code below:
var links = document.links;
for (var i = 0; i < links.length; i++) {
if (!links[i].target) {
if (
links[i].hostname !== window.location.hostname ||
/\.(?!html?)([a-z]{0,3}|[a-zt]{0,4})$/.test(links[i].pathname)
) {
links[i].target = '_blank';
}
}
}
Automated for external links only, using GNU sed & make
If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed command once the (X)HTML has been created from Markdown:
sed -i 's|href="http|target="_blank" href="http|g' index.html
This can be further automated by adding above sed command to a makefile. For details, see GNU make or see how I have done that on my website.
If you just want to do this in a specific link, just use the inline attribute list syntax as others have answered, or just use HTML.
If you want to do this in all generated <a> tags, depends on your Markdown compiler, maybe you need an extension of it.
I am doing this for my blog these days, which is generated by pelican, which use Python-Markdown. And I found an extension for Python-Markdown Phuker/markdown_link_attr_modifier, it works well. Note that an old extension called newtab seems not work in Python-Markdown 3.x.
For React + Markdown environment:
I created a reusable component:
export type TargetBlankLinkProps = {
label?: string;
href?: string;
};
export const TargetBlankLink = ({
label = "",
href = "",
}: TargetBlankLinkProps) => (
<a href={href} target="__blank">
{label}
</a>
);
And I use it wherever I need a link that open in a new window.
For "markdown-to-jsx" with MUI v5
This seem to work for me:
import Markdown from 'markdown-to-jsx';
...
const MarkdownLink = ({ children, ...props }) => (
<Link {...props}>{children}</Link>
);
...
<Markdown
options={{
forceBlock: true,
overrides: {
a: {
component: MarkdownLink,
props: {
target: '_blank',
},
},
},
}}
>
{description}
</Markdown>
This works for me: [Page Link](your url here "(target|_blank)")
Related
I am working on an application where user can add comments to certain fields. these comments can also be links. So, as a user I want to be able to click on those links rather than copy pasting them in a new tab.
If a normal web link ([http://|http:]... or [https://|https:]...) occurs in a comment/attribute value, it should be presented as a clickable link.
Multiple links may occur in the same comment/attribute value.
Clicking on a link opens a new browser tab that calls up this link.
This is how the formControl is being managed. I think i can identify multiply links with the help of regex but how do I make them clickable as well?
Thanks for answering and helping in advance.
this.formControl = new FormControl('', [this.params.customValidations(this.params)]);
this.formControl.valueChanges.subscribe(() => {
this.sendStatusToServices();
});
Outside the form editor/input (most likely what you're looking for)
Either before saving the value of the Form Field to the Database, or editing the received body from the database just before presenting to the user, you can use Regex to replace links with anchor tags.
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
Rich text editor
If however, you're trying to enable links INSIDE the form input (like WordPress's text editor), that's going to be a bit more difficult. You'll need a <textarea> to enable custom HTML elements. Then you need to detect when the user has typed a URL, so you can call replaceURLWithHTMLLinks(). Honestly, you should just use a package. There's several good one out there.
Angular Rich Text Editor - A WYSIWYG Markdown Editor, by SyncFusion
NgxEditor, by sibiraj-s
typester-editor
Hope this helps
Using a regex approach and a pipe I was able to come up with something like below.
What I'm doing is replacing the links with hyperlink tags using a proper regex.
url replacement regex is taken from here
Supports multiple links within same comment.
Here is the sample pipe code
#Pipe({
name: 'comment'
})
export class CommentPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer){}
transform(value: any, args?: any): any {
const replacedValue = this.linkify(value);
return this.sanitizer.bypassSecurityTrustHtml(replacedValue)
}
// https://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links#21925491
// this method is taken from above answer
linkify(inputText: string) {
var replacedText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/gim;
replacedText = inputText.replace(replacePattern1, '$1');
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1$2');
//Change email addresses to mailto:: links.
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+#[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '$1');
return replacedText;
}
}
Here is the completed stackblitz
If you want links within Input itself you might want to try different approach
So I'm using TailwindCSS for a WP theme I'm developing.
I ran into an issue in creating the production grade theme files because, from how I understand the problem, purgecss can't recognize conditional classes used on template parts. For example, let's say I created a template part called "business-card.php" where I pass it a variable type (using set_query_var / get_query_var):
page-about.php
set_query_var('type', 'A');
get_template_part('template-parts/content/business', 'card');
set_query_var('type', 'B');
get_template_part('template-parts/content/business', 'card');
businesss-card.php
$type = get_query_var('type')
<div class="<?php echo type == 'A' ? 'text-color-A' : 'text-color-B' ?>">
--- insert some content here ---
</div>
So there will be two divs, one will have a text-color-A class, the other will have a text-color-B, both were created using a config file(rather than included in the base tailwind theme). This is fine in development -- since tailwind does actually create the utility color classes from the config file. But for some reason, when it's in production (i.e. purged & minified), it doesn't have those utility classes -- which were only used in the template part as conditional classes (and not in any other file).
PurgeCSS is intentionally very naive in the way it looks for classes in your HTML. It doesn't try to parse your HTML and look for class attributes or dynamically execute your JavaScript — it simply looks for any strings in the entire file that match this regular expression:
/[^<>"'`\s]*[^<>"'`\s:]/g
That means that it is important to avoid dynamically creating class strings in your templates with string concatenation, otherwise PurgeCSS won't know to preserve those classes.
So do not use string concatenation to create class names:
<div :class="text-{{ error ? 'red' : 'green' }}-600"></div>
Instead, dynamically select a complete class name:
<div :class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
As long as a class name appears in your template in its entirety, PurgeCSS will not remove it.
See the docs for more details:
Writing purgeable HTML
If you are using Tailwind 2.0+ you can configure whitelisted classes that will be ignored by purge CSS directly inside of your tailwind.config.js file.
An example of my own code where I whitelist the class text-ingido-400 can be seen below
// tailwind.config.js
module.exports = {
purge: {
content: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
options: {
safelist: ['text-indigo-400']
}
} ,
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
For more information you can check out the relevant documentation located at:
https://tailwindcss.com/docs/optimizing-for-production
You can use the PurgeCSS whitelist option to add those classes.
const purgecss = new Purgecss({
//... Your config
whitelist: ['text-color-A', 'text-color-B', 'etc']
})
Or the whitelistPatterns (Regex match)
whitelistPatterns: [/^text-color/], // All classes starting with text-color
You can find more information here
If you define your class names in a variable above where you want to use them it works akin to safe listing them in Tailwind or whitelisting them in PurgeCSS, is potentially easier to maintain, and works good in a pinch if you have a small number of possbile dynamic class names.
var classes =`grid-cols-1 grid-cols-2 grid-cols-3 grid-cols-4`
return (
<div className={`grid grid-cols-${items['grid-cols']}`}>
</div>
)
For some tailwindcss class, you can use inline style instead.
Inline style allow you to use dynamic value, like <div style="padding-left:{indent}rem">.
I think it works in php also. More details can be found here
I have Visual Studio 2012 Express installed in Windows 8.1 OS and using CKEditor in my project as per requirement.
I am new for CKEditor and using it in a proper way as well but the problem is by defining the html in source in CKEditor it replaces automatically
<div><i class="classname"></i></div>
with
<div> </div> or <div></div>
So How to prevent CKEditor not to replace it and save as it is?
I have got some solution but still little bit error I am replacing
<i class="classname"></i>
with
<div class="classname"></div>
but in between the tag it automatically add  .
How to prevent it to not add  ?
Here in below image is CKEditor is open and you can see in rounded area it automatically adds some space or tab in my code.
How to stop that?
Have a look at this Post:
CKEditor unwanted characters
After some research I might shed some light on this issue -
unfortunately there is no out-of-the-box solution.
In the CKEditor there are four ways a no-break space can occur (anybody knows more?):
Automatic filling of empty blocks. This can be disabled in the config:
config.fillEmptyBlocks = false;
Automatic insertion when pressing TAB-key. This can be diabled in the config:
config.tabSpaces = 0;
Converting double spaces to SPACE+NBSP. This is a browser behavior and will thus not be fixed by the CKEditor team. It could be fixed
serverside or by a clientside javascript onunload. Maybe this php is a
start:
preg_replace('/\s \s/i', ' ', $text);
By copy&paste. If you paste a UTF-8 no-break space or double-spaces CKEditor will convert it automatically. The only
solution I see here is doing a regex as above.
config.forcePasteAsPlainText = true; doesn't help.
Summary: To get rid of all no-break spaces you need to write an
additional function that cleans user input.
Comments and further suggestions are greatly appreciated! (I'm using ckeditor
3.6.4)
EDIT #1
Have a look at this.
CKEDITOR.dtd.$removeEmpty.i= 0;
You can also can use this with span and other tags.
The documentation to this.
Stop Removing ANY Empty Tag in CKEditor
There is a defined list of tags that is going to be removed if
empty(see dtd.js and $removeEmpty or run CKEDITOR.dtd.$removeEmpty
from console).
From HTmL
To ensure the certain empty tag are not being removed, add attribute
‘data-cke-survive’:
<span data-cke-survive="true" ></span>
From Configurations
Or you can configure the particular tag from not be removed:
if(window.CKEDITOR){
CKEDITOR.on('instanceCreated', function (ev) {
CKEDITOR.dtd.$removeEmpty['span'] = 0;
CKEDITOR.dtd.$removeEmpty['TAG-NAME'] = 0;
}
}
By setting an element to 0 in the CKEDITOR.dtd.$removeEmpty, it
prevents the empty tags from being removed by CKEditor.
http://margotskapacs.com/
This topic can be helpfull https://stackoverflow.com/
In short- You can disable Automatic filling of empty blocks in the config:
config.fillEmptyBlocks = false;
more information- here
UPD.
You can try this config.protectedSource.push(/<i[^>]*><\/i>/g);
From official documentation
{Array} CKEDITOR.config.protectedSource Since: 3.0
List of regular expressions to be executed on input HTML, indicating HTML source code that when matched, must not be available in the WYSIWYG mode for editing.
config.protectedSource.push( /<\?[\s\S]*?\?>/g ); // PHP code
config.protectedSource.push( /<%[\s\S]*?%>/g ); // ASP code
config.protectedSource.push( /(]+>[\s|\S]*?</asp:[^>]+>)|(]+/>)/gi ); // ASP.Net code
UPD 2
Hope this will help.
CKEDITOR.on( 'instanceReady', function( ev )
{
// turn off excess line breaks in html output formatting for blockquote tag.
// In same way you can correct any tag output formating
ev.editor.dataProcessor.writer.setRules( 'blockquote',
{
indent : false,
breakBeforeOpen : false,
breakAfterOpen : false,
breakBeforeClose : false,
breakAfterClose : true
});
});
For the one who are using UniSharp/laravel-ckeditor
<script>
var options = {
fillEmptyBlocks: false,
};
CKEDITOR.replace( 'content', options);
</script>
I want to add CSS to pages with a certain URL in much the same way that Greasemonkey adds JavaScript. I guess I could inject some CSS with a script, but that isn't as clean.
Are there any browser plugins that let me do this? It doesn't necessarily need to be a Firefox one.
There's the Stylish add-on for Firefox. It supports global, per-domain, and per-URL user stylesheets. It seems to work well for what I use it for, although I admittedly haven't played around with it very seriously.
If you have access to jQuery, you could do this pretty easily:
var css_href = "path to css";
var head = document.getElementsByTagName('head')[0];
$(document.createElement('link'))
.attr({ type: 'text/css',
href: css_href,
rel: 'stylesheet,
media: 'screen''})
.appendTo(head);
[Source]
This can also be done pretty easily with vanilla JavaScript:
function addStyle(style) {
var head = document.getElementsByTagName("HEAD")[0];
var ele = head.appendChild(window.document.createElement( 'style' ));
ele.innerHTML = style;
return ele;
}
addStyle('#import "/URL/TO/STYLESHEET;"');
[Source] (Apparently from "Dive into Greasemonkey" by Mark Pilgrim originally)
You might want to make sure your styles have !important declarations though.
Having said that, it should be easy to remove the existing stylesheets this way too and perhaps even iterate elements and remove inline styles.
The place were I wnat to use the YUI DataTable is in a wiki that allows HTML and javascript. I have created the custom table, put it in a div and gave it an ID and it works really well except that it usees the CSS from the container wiki page and visually it is not presentable. I would like to be able to set the CSS information for this particular table so that it is more readable. As you might guess I cannot modify the "head" information as the wiki only allows me to add things to the "body" of the html. I am by no means an expert in html and as such I am not sure if can specify CSS for a one table?
I was looking around in the YUI documentation to see if there was a mechansim in the YUI DataTable to set the CSS type of information but I could not really find anything. It seems like I should be able to set it in the oConfig object I pass to the table when it is created. So if someone knows of a way to do it using the YUI DataTable parameters that would be appreciated as well.
Can you run Javascript in the page? If so, then you can dynamically add a css link to the page without access to the element.
Here's how from the open source Timeline project:
// Use document for the doc param
function includeCssFile(doc, url) {
if (doc.body == null) {
try {
doc.write("<link rel='stylesheet' href='" + url + "' type='text/css'/>");
return;
} catch (e) {
// fall through
}
}
var link = doc.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", url);
getHead(doc).appendChild(link);
};
function getHead(doc) {
return doc.getElementsByTagName("head")[0];
};
Put your datatable in a specific div with an id
Or: Via the css selector : #yourdivid .yui-dt-data