msos/preferred-source.js

65 lines
2.7 KiB
JavaScript

/* MSOS — "Add as a preferred source on Google".
* (1) A small text link in the footer (.legal-links) on every page.
* (2) An interactive pill button on the homepage, News hub and Blog hub
* (Google's official button via publisher.js; renders any element with
* the google-add-preferred-source-btn attribute).
* Self-contained, no dependencies. Domain-level deeplink works everywhere;
* the pill needs Google's library, loaded only on the hub pages. */
(function () {
var DEEPLINK = 'https://www.google.com/preferences/source?q=msosorg.com';
var docLang = (document.documentElement.getAttribute('lang') || 'en').toLowerCase();
var lang = docLang === 'sl' ? 'si' : (['en', 'mk', 'si'].indexOf(docLang) === -1 ? 'en' : docLang);
var btnLang = lang === 'si' ? 'sl' : lang; // Google button uses ISO code (sl)
var L = {
en: { footer: 'Add us on Google', full: 'Add MSOS as a preferred source on Google' },
mk: { footer: 'Додади нè на Google', full: 'Додади нè како префериран извор на Google' },
si: { footer: 'Dodaj nas na Google', full: 'Dodajte nas kot prednostni vir na Googlu' }
}[lang];
// (1) Footer link — appended once into .legal-links.
function addFooterLink() {
var box = document.querySelector('.legal-links');
if (!box || box.querySelector('.js-preferred-source')) return;
var a = document.createElement('a');
a.className = 'js-preferred-source';
a.href = DEEPLINK;
a.target = '_blank';
a.rel = 'noopener';
a.title = L.full;
a.textContent = L.footer;
box.appendChild(a);
}
// (2) Interactive pill — only on homepage / news hub / blog hub.
function isHub() {
var p = location.pathname;
if (p.charAt(p.length - 1) !== '/') p += '/';
return /^\/(en|mk|si)\/$/.test(p) || /^\/(en|mk|si)\/(news|blog)\/$/.test(p);
}
function addPill() {
if (!isHub() || document.getElementById('msos-prefsrc')) return;
var anchor = document.querySelector('main h1') || document.querySelector('h1');
if (!anchor) return;
var wrap = document.createElement('div');
wrap.id = 'msos-prefsrc';
wrap.className = 'msos-prefsrc';
wrap.style.margin = '14px 0 4px';
var btn = document.createElement('div');
btn.setAttribute('google-add-preferred-source-btn', '');
btn.setAttribute('data-lang', btnLang);
wrap.appendChild(btn);
anchor.insertAdjacentElement('afterend', wrap);
var s = document.createElement('script');
s.async = true;
s.src = 'https://news.google.com/swg/js/v1/publisher.js';
document.head.appendChild(s);
}
function init() { addFooterLink(); addPill(); }
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
else init();
})();