diff --git a/lib/plugins/helper/open_graph.js b/lib/plugins/helper/open_graph.js index 9506bb00e3..35d8beb12e 100644 --- a/lib/plugins/helper/open_graph.js +++ b/lib/plugins/helper/open_graph.js @@ -1,6 +1,5 @@ 'use strict'; -const { parse, resolve } = require('url'); const { isMoment, isDate } = require('moment'); const { encodeURL, prettyUrls, htmlTag, stripHTML, escapeHTML } = require('hexo-util'); const { default: moize } = require('moize'); @@ -56,7 +55,6 @@ const og = (name, content, escape) => { }; function openGraphHelper(options = {}) { - const { config, page } = this; const { content } = page; let images = options.image || options.images || page.photos || []; @@ -117,15 +115,7 @@ function openGraphHelper(options = {}) { result += og('og:locale', localeToTerritory(language), false); } - images = images.map(path => { - if (!parse(path).host) { - // resolve `path`'s absolute path relative to current page's url - // `path` can be both absolute (starts with `/`) or relative. - return resolve(url || config.url, path); - } - - return path; - }); + images = images.map(path => new URL(path, url || config.url).toString()); images.forEach(path => { result += og('og:image', path, false); @@ -161,9 +151,7 @@ function openGraphHelper(options = {}) { if (options.twitter_image) { let twitter_image = options.twitter_image; - if (!parse(twitter_image).host) { - twitter_image = resolve(url || config.url, twitter_image); - } + twitter_image = new URL(twitter_image, url || config.url); result += meta('twitter:image', twitter_image, false); } else if (images.length) { result += meta('twitter:image', images[0], false); diff --git a/test/scripts/helpers/open_graph.js b/test/scripts/helpers/open_graph.js index f8b78ffb61..c709e7fa17 100644 --- a/test/scripts/helpers/open_graph.js +++ b/test/scripts/helpers/open_graph.js @@ -301,11 +301,10 @@ describe('open_graph', () => { }); it('images - resolve relative path when site is hosted in subdirectory', () => { - const urlFn = require('url'); const config = hexo.config; - config.url = urlFn.resolve(config.url, 'blog'); + config.url = new URL('blog', config.url).toString(); config.root = 'blog'; - const postUrl = urlFn.resolve(config.url, '/foo/bar/index.html'); + const postUrl = new URL('/foo/bar/index.html', config.url).toString(); const result = openGraph.call({ page: {}, @@ -314,7 +313,7 @@ describe('open_graph', () => { url: postUrl }, {images: 'test.jpg'}); - result.should.have.string(meta({property: 'og:image', content: urlFn.resolve(config.url, '/foo/bar/test.jpg')})); + result.should.have.string(meta({property: 'og:image', content: new URL('/foo/bar/test.jpg', config.url).toString()})); }); it('twitter_image - default same as og:image', () => {