Skip to content

Commit

Permalink
refactor(external_link): use whatwg url
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Oct 28, 2019
1 parent 3222513 commit 98fd59a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
18 changes: 12 additions & 6 deletions lib/plugins/filter/after_post_render/external_link.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
'use strict';

const { parse } = require('url');
const urlObj = (str) => {
try {
return new URL(str);
} catch (err) {
return str;
}
};

const isExternal = (url, config) => {
const exclude = Array.isArray(config.external_link.exclude) ? config.external_link.exclude :
[config.external_link.exclude];
const data = parse(url);
const data = urlObj(url);
const host = data.hostname;
const sitehost = parse(config.url).hostname || config.url;
const sitehost = urlObj(config.url).hostname || config.url;

if (!data.protocol || !sitehost) return false;
if (!data.protocol || !sitehost || !data.origin) return false;

if (exclude && exclude.length) {
for (const i of exclude) {
Expand All @@ -34,10 +40,10 @@ function externalLinkFilter(data) {
}, config.external_link);
}
if (config.external_link === false || config.external_link.enable === false ||
config.external_link.field !== 'post') return;
config.external_link.field !== 'post') return;

data.content = data.content.replace(/<a.*?(href=['"](.*?)['"]).*?>/gi, (str, hrefStr, href) => {
if (/target=/gi.test(str) || href.startsWith('mailto:') || href.startsWith('javascript:') || !isExternal(href, config)) return str;
if (/target=/gi.test(str) || !isExternal(href, config)) return str;

if (/rel=/gi.test(str)) {
str = str.replace(/rel="(.*?)"/gi, (relStr, rel) => {
Expand Down
16 changes: 12 additions & 4 deletions lib/plugins/filter/after_render/external_link.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
'use strict';

const { parse } = require('url');
const { URL } = require('url');

const urlObj = (str) => {
try {
return new URL(str);
} catch (err) {
return str;
}
};

/**
* Check whether the link is external
Expand All @@ -11,11 +19,11 @@ const { parse } = require('url');
const isExternal = (url, config) => {
const exclude = Array.isArray(config.external_link.exclude) ? config.external_link.exclude :
[config.external_link.exclude];
const data = parse(url);
const data = urlObj(url);
const host = data.hostname;
const sitehost = parse(config.url).hostname || config.url;
const sitehost = urlObj(config.url).hostname || config.url;

if (!data.protocol || !sitehost) return false;
if (!data.protocol || !sitehost || !data.origin) return false;

if (exclude && exclude.length) {
for (const i of exclude) {
Expand Down

0 comments on commit 98fd59a

Please sign in to comment.