- JavaScript | Как получить код HTML-страницы?
- Как объект document превратить в строку с HTML-разметкой?
- Одной командой
- Видео инструкция
- Задача
- Немножко теории
- Решение
- Итог
- Get HTML Content With Javascript Fetch (Simple Example)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- JAVASCRIPT FETCH CONTENT
- PART 1) THE HTML
- PART 2) THE JAVASCRIPT
- PART 3) DUMMY HTML
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- RETURN AS OTHER DATA TYPES?
- FETCHING HTML FROM ANOTHER SITE?
- COMPATIBILITY CHECKS
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
- 2 thoughts on “Get HTML Content With Javascript Fetch (Simple Example)”
- JavaScript | Как получить весь текст на HTML-странице?
- Видео инструкция
- Решение вопроса
- Итог
- Get HTML From URL in JavaScript
- Use XMLHttpRequest() to Get HTML Code With a URL
- Use jQuery to Get HTML Code With a URL
JavaScript | Как получить код HTML-страницы?
Как объект document превратить в строку с HTML-разметкой?
Одной командой
new XMLSerializer().serializeToString(document)
Куда вводить эту команду? Открываете HTML-страницу, с которой хотите получить все веб-ссылки. Включаете «Инструменты разработчика» в браузере (CTRL + SHIFT + i). Находите вкладку «Console«. Тыкаете курсор в белое поле справа от синей стрелочки. Вставляете команду. Жмёте клавишу ENTER.
Для тех кто не понял строчку кода выше, предлагаю упрощённую для понимания версию. Пошаговая инструкция и видео ниже.
Видео инструкция
В этом видео приводится пример преобразования HTML-элемента в строку при помощи JavaScript. Ввод команд осуществляется в консоль браузера Google Chrome. Результат виден сразу.
Задача
У нас открыта вкладка в браузере. В этой вкладке отрисована HTML-страница, которая пришла с сервера.
Нам нужно получить код данной HTML-страницы — разметку. Мы хотим получить разметку в виде СТРОКИ. То есть нам как-то нужно преобразовать объект HTML-элемента в строковый тип данных JavaScript.
Немножко теории
«Объектная модель документа» (DOM) преобразовывает СТРОКУ кода c сервера в объект document . Этот объект хранит в себе наборы элементов и их последовательности. Самый правильный сценарий — это сделать GET-запрос на сервер и достать данные при помощи функции fetch(). Но нам нужно понять способ КОНВЕРТАЦИИ из уже готового объекта.
У объекта document есть готовый набор атрибутов, который помогает извлекать данные из страниц. Два атрибута, на которые можно акцентировать внимание — это documentElement и doctype. Но эти данные являются объектами, а не строками.
В данной задаче извлекать их по отдельности не имеет смысла. Просто вы должны понимать структуру объекта document . Внутри объекта тоже объекты, а не строки.
Решение
Нам нужно использовать интерфейс XMLSerializer, который имеет один единственный метод serializeToString(). Этот метод вернёт нам СТРОКУ из ОБЪЕКТА.
Сперва нам нужно создать новый конструктор сериализатора разметки:
Теперь мы можем вызвать метод serializeToString() и передать в него наш объект document .
a.serializeToString(document)
На выходе мы получаем СТРОКУ с HTML-разметкой. Тип данных STRING. Даже консоль браузера нам подсвечивает её красно-коричневым цветом.
typeof(new XMLSerializer().serializeToString(document)) "string"
Можно без объявления лишних переменных сразу получить строку с HTML-разметкой
new XMLSerializer().serializeToString(document)
Итог
Мы выполнили задачу и получили весь код HTML-страницы.
Get HTML Content With Javascript Fetch (Simple Example)
Welcome to a quick tutorial and example of how to get HTML content using the Javascript Fetch API. So you are wondering if fetch() can get HTML content just like XMLHttpRequest ? Of course, we can.
To get HTML content with the Javascript Fetch API, simply make a fetch() call to the script and return the result as text.
- fetch(«PAGE.HTML»)
- .then(res => res.text())
- .then(html => document.getElementById(«ID»).innerHTML = html);
That covers the quick basics, but read on if you need the full example!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
JAVASCRIPT FETCH CONTENT
All right, let us now get into the example of getting HTML content using Javascript fetch.
PART 1) THE HTML
No sweat. Just a to put the loaded contents into, and a to run the fetch content demo.
PART 2) THE JAVASCRIPT
function loadContent () < // (A) FETCH "DUMMY.HTML" fetch("2-dummy.html") // (B) RETURN THE RESULT AS TEXT .then(res => < if (res.status != 200) < throw new Error("Bad Server Response"); >return res.text(); >) // (C) PUT LOADED CONTENT INTO .then(html => document.getElementById("demo").innerHTML = html) // (D) HANDLE ERRORS - OPTIONAL .catch(err => console.error(err)); >
Right, this is pretty much the “expanded version” of the introduction snippet.
- Here, we are making a call to 2-dummy.html . It can be whatever server-side script (PHP, ASP, Python, etc… ) in your own project.
- Take note of if (result.status != 200) < THROW ERROR >. For the uninitiated, fetch() will consider it a success as long as the server responds. That is, even when the server returns a funky 500 (internal server error), 404 (not found), or whatever else server error. We are just doing a manual 200 (OK) check here before returning the contents fetched from the server.
- Captain Obvious, put the fetched contents in the .
- Lastly, handle any errors that may have happened. Optional, but highly recommended.
PART 3) DUMMY HTML
Yep. Just dummy HTML. This can be your own server-side script that generates HTML.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
RETURN AS OTHER DATA TYPES?
FETCHING HTML FROM ANOTHER SITE?
- Please take note that there is something called “same origin policy” – By default, site-a.com can only make fetch calls to site-a.com .
- If you want to make a fetch from site-a.com to site-b.com , this is called “cross origins” (CORS for short).
- It is possible to make a CORS fetch – But only if you own both sites, or the other website is open to let your site access. See the CORS fetch link below.
COMPATIBILITY CHECKS
Will not have any problems on all modern browsers.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
2 thoughts on “Get HTML Content With Javascript Fetch (Simple Example)”
So opening this from my _file system_ results in a CORS (Cross-Origin Resource Sharing) error.
“CORS requests may only use the HTTP or HTTPS URL scheme, but the URL specified by the request is of a different type. This often occurs if the URL specifies a local file, using the file:/// scheme.” https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp
Probably not a surprise. I should be running this on a server (e.g. localhost) using HTTP scheme.
This might be a stumper for some. Maybe consider including a note in your tutorial? Regardless, thanks for the nice little tutorial.
JavaScript | Как получить весь текст на HTML-странице?
Куда вводить эту команду? Открываете HTML-страницу, с которой хотите получить весь текст. Включаете «Инструменты разработчика» в браузере (CTRL + SHIFT + i). Находите вкладку «Console«. Тыкаете курсор в белое поле справа от синей стрелочки. Вставляете команду. Жмёте клавишу ENTER.
Для тех кто не понял длинную строчку кода выше, предлагаю упрощённую для понимания версию. Пошаговая инструкция и видео ниже.
Видео инструкция
В этом видео приводится пример получения всего текста на HTML-странице при помощи JavaScript и объектной модели документа. Ввод команд осуществляется в консоль браузера Google Chrome. Результат виден сразу.
Решение вопроса
Мы будем использовать объектную модель документа — DOM. Обращаемся к объекту document.
Скриншот страницы и вкладки Console:
Мы видим, что объект хранит в себе всю разметку.
Получим «элемент документа» — по сути получим всю разметку страницы (элемент html и его содержимое) + это будет не строка, а набор объектов элементов.
Эта команда отсекла только элемент DOCTYPE. Он нам всё равно не нужен. Эта информация важна только браузеру.
Теперь вся разметка представлена в виде объектов JavaScript. Каждый объект хранит в себе пары «ключ/значение» — с общими и уникальными ключами. Все объекты HTML-элементов имеют ключ innerText. Это значит, что мы сможем получить всё текстовое содержимое каждого парного элемента. Причём получим не только видимый на экране текст, но и скрытый текст (текст может быть скрытым из-за особенностей дизайна сайта и оформления вкладок внутри страницы).
document.documentElement.innerText
Итог
Мы получили весь текст со страницы. Теперь можно разбить весь этот текст на строки и положить в массив. Потом можно разбить полученные предложения на слова. Далее можно составить поисковый индекс и рейтинг слов на странице.
Поисковая фраза — «js all document innertext»
Get HTML From URL in JavaScript
- Use XMLHttpRequest() to Get HTML Code With a URL
- Use jQuery to Get HTML Code With a URL
One can easily see the web page’s source code using browser dev tools.
But the interesting feature that JavaScript provides us is that we can get the source code of a different webpage on our page without having to visit that page. This post shows various methods of achieving this.
Use XMLHttpRequest() to Get HTML Code With a URL
XML HTTP Request (XHR) mainly serves to retrieve data from a URL without refreshing the page. So they can be used to get the HTML code from a different page.
function makeHttpObject() if("XMLHttpRequest" in window)return new XMLHttpRequest(); else if("ActiveXObject" in window)return new ActiveXObject("Msxml2.XMLHTTP"); > var request = makeHttpObject(); request.open("GET", "/", true); request.send(null); request.onreadystatechange = function() if (request.readyState == 4) console.log(request.responseText); >;
In the above example, we first make the HTTP object an HTTP request.
Then we initialize and send the get request using open() and send() methods. We print the HTML code when the response becomes available.
Use jQuery to Get HTML Code With a URL
jQuery.ajax() is used to perform asynchronous HTTP requests. It takes as an argument the URL to send requests and settings (a set of key-value pairs).
$.ajax(< url: '/', success: function(data) < console.log(data); >>);
In the above example, we pass the URL for the HTTP request, and if the request is a success, we print the data returned (i.e., the HTML code for the webpage).
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.