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

report: truncate long attribute values in HTML snippets #10984

Merged
merged 9 commits into from
Jul 15, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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
9 changes: 9 additions & 0 deletions lighthouse-core/lib/page-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ function getElementsInDocument(selector) {
*/
/* istanbul ignore next */
function getOuterHTMLSnippet(element, ignoreAttrs = []) {
const ATTRIBUTE_CHAR_LIMIT = 100;
try {
// ShadowRoots are sometimes passed in; use their hosts' outerHTML.
if (element instanceof ShadowRoot) {
Expand All @@ -123,6 +124,14 @@ function getOuterHTMLSnippet(element, ignoreAttrs = []) {
ignoreAttrs.forEach(attribute =>{
clone.removeAttribute(attribute);
});
for (const attributeName of clone.getAttributeNames()) {
let attributeValue = clone.getAttribute(attributeName);
if (attributeValue.length > ATTRIBUTE_CHAR_LIMIT) {
attributeValue = attributeValue.slice(0, ATTRIBUTE_CHAR_LIMIT - 1) + '…';
clone.setAttribute(attributeName, attributeValue);
}
}

const reOpeningTag = /^[\s\S]*?>/;
const match = clone.outerHTML.match(reOpeningTag);
Copy link
Collaborator

Choose a reason for hiding this comment

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

maybe replace with

const [match] = clone.outerHTML.match(reOpeningTag) || [];

and then drop all the match && match[0] for just match ?

return (match && match[0]) || '';
Expand Down
8 changes: 8 additions & 0 deletions lighthouse-core/test/lib/page-functions-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ describe('Page Functions', () => {
assert.equal(pageFunctions.getOuterHTMLSnippet(
dom.createElement('div', '', {style: 'style1\nstyle2'})), '<div style="style1\nstyle2">');
});

it('truncates attribute values that are too long', () => {
const longClass = 'a'.repeat(200);
const truncatedExpectation = 'a'.repeat(99) + '…';
assert.equal(pageFunctions.getOuterHTMLSnippet(
dom.createElement('div', '', {class: longClass})), `<div class="${truncatedExpectation}">`
);
});
});

describe('getNodeSelector', () => {
Expand Down