This repository was archived by the owner on Dec 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathopen_graph.js
More file actions
56 lines (48 loc) · 1.39 KB
/
open_graph.js
File metadata and controls
56 lines (48 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* Product extraction via Open Graph tags.
*/
import {parsePrice} from 'commerce/extraction/utils';
const OPEN_GRAPH_PROPERTY_VALUES = {
title: 'og:title',
image: 'og:image',
price: 'og:price:amount',
};
/** How product information is extracted depends on the feature */
const FEATURE_DEFAULTS = {
getValueFromElement(element) {
return element.getAttribute('content');
},
};
const PRODUCT_FEATURES = {
image: {
...FEATURE_DEFAULTS,
},
title: {
...FEATURE_DEFAULTS,
},
price: {
...FEATURE_DEFAULTS,
getValueFromElement(element) {
return parsePrice([element.getAttribute('content')]);
},
},
};
/**
* Returns any product information available on the page from Open Graph <meta>
* tags.
*/
export default function extractProduct() {
const extractedProduct = {};
for (const [feature, propertyValue] of Object.entries(OPEN_GRAPH_PROPERTY_VALUES)) {
const metaEle = document.querySelector(`meta[property='${propertyValue}']`);
// Fail early if any required tags aren't found.
if (!metaEle) {
return null;
}
extractedProduct[feature] = PRODUCT_FEATURES[feature].getValueFromElement(metaEle);
}
return extractedProduct;
}