Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update metadata fields from the challenger content #24

Merged
merged 3 commits into from
Dec 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,9 @@ runEager.call(document, {
// short durations of those campaigns/experiments
rumSamplingRate: 10,

// these metadata fields will be updated when replacing content
overrideMetaFields: ['template', 'theme'],

// the storage type used to persist data between page views
// (for instance to remember what variant in an experiment the user was served)
storage: window.SessionStorage,
Expand Down
26 changes: 19 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const MAX_SAMPLING_RATE = 10; // At a maximum we sample 1 in 10 requests
export const DEFAULT_OPTIONS = {
// Generic properties
rumSamplingRate: MAX_SAMPLING_RATE, // 1 in 10 requests
overrideMetaFields: [],
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I considered defaulting this to ['template', 'theme'] but reverted to empty to avoid this being a breaking change. If we aren't concerned about a breaking change, I think the list above is reasonably safe and should cover most cases where metadata affects rendering of the page


// Audiences related properties
audiences: {},
Expand Down Expand Up @@ -88,12 +89,13 @@ export async function getResolvedAudiences(applicableAudiences, options, context
}

/**
* Replaces element with content from path
* Replaces main content from path
* @param {string} path
* @param {HTMLElement} main
* @param {Document} doc
* @param {string[]} overrideMetaFields
* @return Returns the path that was loaded or null if the loading failed
*/
async function replaceInner(path, main) {
async function replaceContent(path, doc, overrideMetaFields) {
try {
const resp = await fetch(path);
if (!resp.ok) {
Expand All @@ -106,7 +108,17 @@ async function replaceInner(path, main) {
const dom = new DOMParser().parseFromString(html, 'text/html');
// do not use replaceWith API here since this would replace the main reference
// in scripts.js as well and prevent proper decoration of the sections/blocks
main.innerHTML = dom.querySelector('main').innerHTML;
doc.querySelector('main').innerHTML = dom.querySelector('main').innerHTML;

// replace metadata fields
overrideMetaFields.forEach((metadataPropName) => {
const attr = metadataPropName && metadataPropName.includes(':') ? 'property' : 'name';
const newMetas = dom.head.querySelectorAll(`meta[${attr}="${metadataPropName}"]`);
const oldMetas = doc.head.querySelectorAll(`meta[${attr}="${metadataPropName}"]`);
oldMetas.forEach((m) => m.remove());
newMetas.forEach((m) => doc.head.append(m));
});

return path;
} catch (e) {
// eslint-disable-next-line no-console
Expand Down Expand Up @@ -481,7 +493,7 @@ export async function runExperiment(document, options, context) {
document.body.classList.add(`experiment-${context.toClassName(experimentConfig.id)}`);
let result;
if (pages[index] !== currentPath) {
result = await replaceInner(pages[index], document.querySelector('main'));
result = await replaceContent(pages[index], document, pluginOptions.overrideMetaFields);
} else {
result = currentPath;
}
Expand Down Expand Up @@ -542,7 +554,7 @@ export async function runCampaign(document, options, context) {

try {
const url = new URL(urlString);
const result = await replaceInner(url.pathname, document.querySelector('main'));
const result = await replaceContent(url.pathname, document, pluginOptions.overrideMetaFields);
window.hlx.campaign.servedExperience = result || window.location.pathname;
if (!result) {
// eslint-disable-next-line no-console
Expand Down Expand Up @@ -598,7 +610,7 @@ export async function serveAudience(document, options, context) {

try {
const url = new URL(urlString);
const result = await replaceInner(url.pathname, document.querySelector('main'));
const result = await replaceContent(url.pathname, document, pluginOptions.overrideMetaFields);
window.hlx.audience.servedExperience = result || window.location.pathname;
if (!result) {
// eslint-disable-next-line no-console
Expand Down