MCPcopy
hub / github.com/ampproject/amphtml / rewriteAttributesForElement

Function rewriteAttributesForElement

src/url-rewrite.js:29–66  ·  view source on GitHub ↗
(
  element,
  attrName,
  attrValue,
  opt_location,
  opt_updateProperty
)

Source from the content-addressed store, hash-verified

27 * @return {string}
28 */
29export function rewriteAttributesForElement(
30 element,
31 attrName,
32 attrValue,
33 opt_location,
34 opt_updateProperty
35) {
36 const tag = element.tagName.toLowerCase();
37 const attr = attrName.toLowerCase();
38 const rewrittenValue = rewriteAttributeValue(tag, attr, attrValue);
39 // When served from proxy (CDN), changing an <a> tag from a hash link to a
40 // non-hash link requires updating `target` attribute per cache modification
41 // rules. @see amp-cache-modifications.md#url-rewrites
42 const isProxy = isProxyOrigin(opt_location || self.location);
43 if (isProxy && tag === 'a' && attr === 'href') {
44 const oldValue = element.getAttribute(attr);
45 const newValueIsHash = rewrittenValue[0] === '#';
46 const oldValueIsHash = oldValue && oldValue[0] === '#';
47
48 if (newValueIsHash && !oldValueIsHash) {
49 // Save the original value of `target` so it can be restored (if needed).
50 if (!element[ORIGINAL_TARGET_VALUE]) {
51 element[ORIGINAL_TARGET_VALUE] = element.getAttribute('target');
52 }
53 element.removeAttribute('target');
54 } else if (oldValueIsHash && !newValueIsHash) {
55 // Restore the original value of `target` or default to `_top`.
56 element.setAttribute('target', element[ORIGINAL_TARGET_VALUE] || '_top');
57 }
58 }
59 if (opt_updateProperty) {
60 // Must be done first for <input> elements to correctly update the UI for
61 // the first change on Safari and Chrome.
62 element[attr] = rewrittenValue;
63 }
64 element.setAttribute(attr, rewrittenValue);
65 return rewrittenValue;
66}
67
68/**
69 * If (tagName, attrName) is a CDN-rewritable URL attribute, returns the

Callers 2

rewriteAttributes_Method · 0.90

Calls 4

isProxyOriginFunction · 0.90
rewriteAttributeValueFunction · 0.85
getAttributeMethod · 0.80
setAttributeMethod · 0.45

Tested by

no test coverage detected