const puppeteer = require('puppeteer');
const path = require('path');
const fs = require('fs');
const os = require('os');
/**
* Test script to run the computedStyleInliner script in Chromium using Puppeteer
* This script loads the fiction story HTML file and executes the style inliner,
* then captures the results for analysis.
*/
const Platform = {
DARWIN: "darwin",
MAC: "mac",
LINUX: "linux",
WIN32: "win32",
WIN64: "win64",
};
function getPlatform() {
const ARCH_X64 = 'x64';
const platform = os.platform();
if (platform === Platform.DARWIN)
return Platform.MAC;
else if (platform === Platform.LINUX)
return Platform.LINUX;
else if (platform === Platform.WIN32)
return (os.arch() === ARCH_X64 ? Platform.WIN64 : Platform.WIN32);
else
throw new Error('Unsupported platform: ' + platform);
}
function getChromiumExecutablePath() {
const folderPath = process.env.CHROMIUM_PATH;
const platform = getPlatform();
let executablePath = '';
if (platform === Platform.MAC)
executablePath = path.join(folderPath, 'Chromium.app', 'Contents', 'MacOS', 'Chromium');
else if (platform === Platform.LINUX) {
executablePath = path.join(folderPath, 'chrome-wrapper');
} else if (platform === Platform.WIN32 || platform === Platform.WIN64)
executablePath = path.join(folderPath, 'chrome.exe');
else
throw new Error('Unsupported platform: ' + platform);
return executablePath;
}
async function testComputedStyleInliner() {
console.log('Starting Computed Style Inliner test...');
let browser;
try {
// Launch Chromium browser
browser = await puppeteer.launch({
executablePath: getChromiumExecutablePath(),
headless: process.env.HEADLESS === 'true', // Set to true for headless mode
devtools: false,
protocolTimeout: 0,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--disable-gpu',
'--auto-open-devtools-for-tabs'
]
});
const page = await browser.newPage();
// Set viewport size
await page.setViewport({ width: 1200, height: 800 });
// Get the absolute path to the fiction story HTML file
const htmlFilePath = path.resolve(__dirname, 'fiction-story.html');
const fileUrl = `file://${htmlFilePath}`;
console.log(`Loading HTML file: ${fileUrl}`);
// Check if the HTML file exists
if (!fs.existsSync(htmlFilePath)) {
throw new Error(`HTML file not found: ${htmlFilePath}`);
}
// Navigate to the HTML file
await page.goto(fileUrl, { waitUntil: 'networkidle0' });
console.log('Page loaded successfully');
// Wait a moment for any initial rendering
await page.waitForTimeout(1000);
// Count elements before style inlining
const elementCountBefore = await page.evaluate(() => {
return document.querySelectorAll('*').length;
});
console.log(`Total elements found: ${elementCountBefore}`);
// Check if the computedStyleInliner script is loaded
const scriptLoaded = await page.evaluate(() => {
return typeof inlineComputedStyles !== 'undefined';
});
let time = 0;
if (!scriptLoaded) {
console.log('ComputedStyleInliner script not found as global function, executing inline...');
// Read and execute the computedStyleInliner script
const scriptPath = path.resolve(__dirname, 'computedStyleInliner.js');
if (!fs.existsSync(scriptPath)) {
throw new Error(`ComputedStyleInliner script not found: ${scriptPath}`);
}
const scriptContent = fs.readFileSync(scriptPath, 'utf8');
time = await page.evaluate(scriptContent);
console.log('ComputedStyleInliner script executed with time:' + time);
} else {
console.log('ComputedStyleInliner script already loaded');
}
// Wait a moment for any final processing
await page.waitForTimeout(500);
// Count elements with inline styles after processing
const elementsWithInlineStyles = await page.evaluate(() => {
const elements = document.querySelectorAll('*');
let count = 0;
elements.forEach(el => {
if (el.getAttribute('style') && el.getAttribute('style').trim() !== '') {
count++;
}
});
return count;
});
console.log(`Elements with inline styles after processing: ${elementsWithInlineStyles}`);
// Get sample of inlined styles for verification
const sampleStyles = await page.evaluate(() => {
const elements = document.querySelectorAll('*');
const samples = [];
let count = 0;
for (let el of elements) {
const style = el.getAttribute('style');
if (style && style.trim() !== '' && count < 10) {
samples.push({
tagName: el.tagName,
className: el.className,
style: style.substring(0, 200) + (style.length > 200 ? '...' : '')
});
count++;
}
}
return samples;
});
// Capture console messages
const consoleMessages = [];
page.on('console', msg => {
console.log(msg);
consoleMessages.push({
type: msg.type(),
text: msg.text()
});
});
// Get the final HTML with inlined styles
const finalHtml = await page.content();
// Save the result to a file for inspection
const outputPath = path.resolve(__dirname, 'output/fiction-story-with-inlined-styles.html');
// Ensure output directory exists
const outputDir = path.dirname(outputPath);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
fs.writeFileSync(outputPath, finalHtml, 'utf8');
console.log(`\nResult saved to: ${outputPath}`);
return {
success: true,
outputPath: outputPath,
};
} catch (error) {
console.error('Error during test execution:', error);
return {
success: false,
error: error.message
};
} finally {
if (browser) {
await browser.close();
console.log('\nBrowser closed');
}
}
}
// Run the test if this script is executed directly
if (require.main === module) {
testComputedStyleInliner()
.then(result => {
if (result.success) {
console.log('\n
process.exit(0);
} else {
console.log('\n
process.exit(1);
}
})
.catch(error => {
console.error('\n
process.exit(1);
});
}
module.exports = { testComputedStyleInliner };
Подробнее здесь: https://stackoverflow.com/questions/797 ... romium-bin