jsdom์ ๋ฌธ์์ <head>
ํ๊ทธ ๋ด๋ถ์ ์ธ๋ผ์ธ์ผ๋ก ์๋ ์คํฌ๋ฆฝํธ๋ฅผ ์คํํ ์ ์์ง๋ง <script src="">
๋ฅผ ํตํด ๋ฌธ์ ํค๋์ ์ฐ๊ฒฐ๋ ์คํฌ๋ฆฝํธ๋ฅผ ์คํํ๋๋ก ํ๋ ค๋ฉด ์ด๋ป๊ฒ ํด์ผ ํฉ๋๊น?
๋ด๊ฐ ์ฌ์ฉํ๋ ์ต์ ์ ๊ฒฝ์ฐ:
{
url: url,
resources: 'usable',
runScripts: 'dangerously',
}
// index.js
const request = require('request')
const jsdom = require('jsdom')
const {JSDOM} = jsdom
const url = 'http://localhost:8000'
request(url, (error, response, body) => {
const options = {
url: url,
resources: 'usable',
runScripts: 'dangerously',
}
const dom = new JSDOM(body, options)
console.log(dom.window.document.body.children.length) // Expecting to see `1`
console.log(dom.window.document.body.innerHTML) // Expecting to see `<h1>Hello world</h1>`
})
// external.js
document.addEventListener('DOMContentLoaded', () => {
document.write('<h1>Hello world!</h1>')
})
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSDOM test</title>
<script src="external.js"></script>
</head>
<body>
</body>
</html>
์์ ํ ์ต์ ์์ ์์ : https://github.com/cg433n/jsdom-test
์ฌ๊ธฐ์ ๋ฌธ์ ๋ DOMContentLoaded
๊ฐ ๋น๋๊ธฐ์ ์ด๋ฒคํธ๋ผ๋ ๊ฒ์
๋๋ค. ๋น์ ์ ๊ทธ๊ฒ์ด ์ผ์ด๋ ๊ธฐํ๊ฐ ์๊ธฐ ์ ์ ๊ธฐ๋กํ๊ณ ์์ต๋๋ค. ๋ถ์ด ๋ถ์ ๋๊น์ง ๊ธฐ๋ค๋ ค์ผ ํฉ๋๋ค. ๊ทธ๋์ผ๋ง document.write()
๊ฐ ๋ฐ์ํฉ๋๋ค.
์๋ง๋ ๋ค์๊ณผ ๊ฐ์ด ์๋ํด์ผ ํฉ๋๋ค.
const dom = new JSDOM(body, options)
dom.window.document.addEventListener('DOMContentLoaded', () => {
// We need to delay one extra turn because we are the first DOMContentLoaded listener,
// but we want to execute this code only after the second DOMContentLoaded listener
// (added by external.js) fires.
setImmediate(() => {
console.log(dom.window.document.body.children.length) // Expecting to see `1`
console.log(dom.window.document.body.innerHTML) // Expecting to see `<h1>Hello world</h1>`
});
});
๋ด๊ฐ ์ฐธ์กฐ! ์ฌ๋ฌ๋ถ์ ํ์์ ์ ๋๋ค. ๊ณ์ํด์ ์ข์ ์ผ์ ํ์ญ์์ค!
์๋ฆผ: ์ ๋ฐ๋ชจ์ 2๊ฐ์ง ๊ธฐ๋ฅ์ ์ํํฉ๋๋ค.
request
์(๋) ๊ฐ๊ฐ์๊ฐ๋ฉ๋๋ค. npm install request
๊ฒฐ๊ณผ:setImmediate
๋ ์ฅ๊ธฐ์ ์ผ๋ก ์ํํฉ๋๋ค .๋๋ fs
FS.read()
์ฌ์ฉํ์ฌ ํ์ผ์์ js ์ฝ๋๋ฅผ ์ฝ๊ณ ๋ก๋ํ๋ ๊ฒ์ด ์ข์ต๋๋ค addEventListener()
#1914. ๋ด๊ฐ ์ ์ํ๋ ์์
๋ฐ๋ชจ์๋ ๋ค์์ด ํฌํจ๋ฉ๋๋ค.
fs.readFileSync
๋ฅผ ์ฌ์ฉํ์ฌ ์ธ๋ถ js๋ฅผ html์ ๋ฌธ์์ด๋ก ๋ก๋์ด๋ xhr/API ํธ์ถ์ ์ํํ์ง ๋ชปํ๊ฒ ํ์ฌ ๋ถ๋ถ์ ์ผ๋ก๋ง ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์ต๋๋ค.
URL ์์
์ ์ป๋ ๋ฐฉ๋ฒ์ ์ ์ ์์์ต๋๋ค.
์ด์์ ์ผ๋ก๋ URL ์์
๋ฐ๋ชจ๋ฅผ ํตํด external.js ํ์ผ์ ๋ก๋ํ๋ ์
๋ฐ์ดํธ๋ ์ต์ JSDOM ์ ํ์ํฉ๋๋ค. :๋ง์:
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
์ฌ๊ธฐ์ ๋ฌธ์ ๋
DOMContentLoaded
๊ฐ ๋น๋๊ธฐ์ ์ด๋ฒคํธ๋ผ๋ ๊ฒ์ ๋๋ค. ๋น์ ์ ๊ทธ๊ฒ์ด ์ผ์ด๋ ๊ธฐํ๊ฐ ์๊ธฐ ์ ์ ๊ธฐ๋กํ๊ณ ์์ต๋๋ค. ๋ถ์ด ๋ถ์ ๋๊น์ง ๊ธฐ๋ค๋ ค์ผ ํฉ๋๋ค. ๊ทธ๋์ผ๋งdocument.write()
๊ฐ ๋ฐ์ํฉ๋๋ค.์๋ง๋ ๋ค์๊ณผ ๊ฐ์ด ์๋ํด์ผ ํฉ๋๋ค.