seo-manager-pro
Version:
A powerful SEO meta and schema manager for Angular, React, Vue and Vanilla JS apps.
73 lines (72 loc) • 2.69 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SeoManagerPro = void 0;
class SeoManagerPro {
static updateSeo(config) {
var _a, _b;
this.clearPrevious();
if (config.title)
document.title = config.title;
if (config.description) {
this.updateMeta('description', config.description);
this.updateMeta('og:description', config.description);
}
if (config.image) {
this.updateMeta('og:image', config.image);
}
if (config.canonicalUrl) {
this.updateCanonical(config.canonicalUrl);
}
if (config.robots) {
this.updateMeta('robots', config.robots);
}
if ((_a = config.customMetaTags) === null || _a === void 0 ? void 0 : _a.length) {
config.customMetaTags.forEach(tag => {
this.updateMeta(tag.name, tag.content);
});
}
if ((_b = config.schema) === null || _b === void 0 ? void 0 : _b.length) {
config.schema.forEach(sch => {
this.addSchema(sch.type, sch.data);
});
}
}
static updateMeta(name, content) {
let tag = document.querySelector(`meta[name="${name}"]`) || document.querySelector(`meta[property="${name}"]`);
if (!tag) {
tag = document.createElement('meta');
if (name.startsWith('og:')) {
tag.setAttribute('property', name);
}
else {
tag.setAttribute('name', name);
}
document.head.appendChild(tag);
}
tag.setAttribute('content', content);
}
static updateCanonical(url) {
let link = document.querySelector('link[rel="canonical"]');
if (!link) {
link = document.createElement('link');
link.rel = 'canonical';
document.head.appendChild(link);
}
link.href = url;
}
static addSchema(type, data) {
const script = document.createElement('script');
script.type = 'application/ld+json';
script.textContent = JSON.stringify(Object.assign({ '@context': 'https://schema.org', '@type': type }, data));
script.className = 'dynamic-schema';
document.head.appendChild(script);
}
static clearPrevious() {
const oldSchemas = document.querySelectorAll('script.dynamic-schema');
oldSchemas.forEach(script => script.remove());
const oldCanonical = document.querySelector('link[rel="canonical"]');
if (oldCanonical)
oldCanonical.remove();
}
}
exports.SeoManagerPro = SeoManagerPro;