Как найти код скрипта

Updated: 03/12/2022 by

JavaScript or JS logo

Many web pages utilize JavaScript to add dynamic and immersive elements for viewers. Some web developers may want to learn how to create the same elements and effects for their web pages. Viewing the JavaScript code for a web page helps developers learn and implement similar elements.

There are two main ways to view the JavaScript code used on a web page. Select from the list below to learn about each method.

View web page source code

View HTML source code

Some web pages have JavaScript inline with the rest of the HTML source code. Web developers sometimes add JavaScript directly in the HTML when that JavaScript is used only on one web page.

For most browsers, to view inline JavaScript in the HTML source code, do one of the following.

  • Press the Ctrl+U keyboard shortcut.
  • Right-click an empty area on the web page and select the View page source or similar option in the pop-up menu.

Using either method above, the HTML source code is displayed. To find inline JavaScript code, look for a <script type=”text/javascript”> tag, denoting the start of the JavaScript.

Tip

If the JavaScript is contained in a .js file, all modern browsers make the URL for the .js file a hyperlink. Clicking the .js URL hyperlink opens the JavaScript in the source window.

Inspect web page elements

Inspect web page for JavaScript

If JavaScript is used on multiple web pages, it is often referenced in the HTML code through a link to a .js file containing the JavaScript. Using a .js file allows a web developer to change JavaScript code once and apply it to all their web pages.

To view JavaScript contained in a .js file, select your browser below.

  • Chrome
  • Firefox
  • Microsoft Edge
  • Opera
  • Safari

Google Chrome logo

Chrome

  1. Open Chrome and navigate to the web page containing the JavaScript you want to view.
  2. Right-click an empty area on the web page and select Inspect in the pop-up menu to open the Chrome developer tools.

Tip

You can also press F12 on your keyboard to open the developer tools.

  1. In the top-left section of the developer tools, make sure Elements (A) is selected at the top.
  2. In the condensed code under the Elements header, find the <script> tag containing a link to a .js file (B).

Chrome developer tools - reference to .js JavaScript file

  1. Place your mouse cursor over the .js file link, right-click that link, and select Reveal in Sources panel in the pop-up menu.

Chrome developer tools - link to .js JavaScript file

  1. The Sources panel is displayed in the developer tools, showing the lines of JavaScript code contained in the .js file. The name of the .js file is also listed at the top of the Sources panel.

Chrome developer tools - Sources panel showing JavaScript code

Firefox logo

Firefox

  1. Open Firefox and navigate to the web page containing the JavaScript you want to view.
  2. Right-click an empty area on the web page and select Inspect in the pop-up menu to open the Firefox web developer tool.

Tip

You can also press F12 on your keyboard to open the web developer tool.

  1. In the top-left section of the developer tool, make sure Inspector (A) is selected at the top.
  2. In the condensed code under the Inspector header, find the <script> tag containing a link to a .js file (B).

Firefox web developer tool - reference to .js JavaScript file

  1. Place your mouse cursor over the .js file link, right-click that link, and select Open File in Debugger in the pop-up menu.

Firefox web developer tool - link to .js JavaScript file

  1. The Debugger panel is displayed in the web developer tool, showing the lines of JavaScript code contained in the .js file. The name of the .js file is also listed at the top of the Debugger panel.

Firefox web developer tool - Sources panel showing JavaScript code

Microsoft Edge logo

Microsoft Edge

  1. Open Microsoft Edge and navigate to the web page containing the JavaScript you want to view.
  2. Right-click an empty area on the web page and select Inspect in the pop-up menu to open the Edge developer tools.

Tip

You can also press F12 on your keyboard to open the developer tools.

  1. In the top-left section of the developer tools, make sure Elements (A) is selected at the top.
  2. In the condensed code under the Elements header, find the <script> tag containing a link to a .js file (B).

Edge developer tools - reference to .js JavaScript file

  1. Place your mouse cursor over the .js file link, right-click that link, and select Reveal in Sources panel in the pop-up menu.

Edge developer tools - link to .js JavaScript file

  1. The Sources panel is displayed in the developer tools, showing the lines of JavaScript code contained in the .js file. The name of the .js file is also listed at the top of the Sources panel.

Edge developer tools - Sources panel showing JavaScript code

Opera browser logo

Opera

  1. Open Opera and navigate to the web page containing the JavaScript you want to view.
  2. Right-click an empty area on the web page and select Inspect element in the pop-up menu to open the Opera developer tools.

Tip

You can also press Ctrl+Shift+C on your keyboard to open the developer tools.

  1. In the top-left section of the developer tools, make sure Elements (A) is selected at the top.
  2. In the condensed code under the Elements header, find the <script> tag containing a link to a .js file (B).

Opera developer tools - reference to .js JavaScript file

  1. Place your mouse cursor over the .js file link, right-click that link, and select Reveal in Sources panel in the pop-up menu.

Opera developer tools - link to .js JavaScript file

  1. The Sources panel is displayed in the developer tools, showing the lines of JavaScript code contained in the .js file. The name of the .js file is also listed at the top of the Sources panel.

Opera developer tools - Sources panel showing JavaScript code

Safari logo

Safari

Note

If you already have the Safari developer tools enabled, skip to step 6.

  1. Open the Safari browser.
  2. Select Safari selector from the menu bar at the top-left corner of the screen.
  3. In the drop-down menu that appears, select Preferences.

Preferences selector

  1. Click the Advanced tab, and check the box next to Show Develop menu in menu bar.

Show Develop menu in Safari.

  1. You should now see the Develop selector in the Apple menu bar at the top of the screen.

Develop selector in Apple menu bar.

  1. Navigate to the web page where you want to view the JavaScript code.
  2. In the Apple menu bar, click Develop and select Show Web Inspector.
  3. In the top-right section of the developer tool, make sure Elements (A) is selected at the top.
  4. In the condensed code under the Elements header, find the <script> tag containing a link to a .js file (B).

Tip

You may need to expand the <head> or <body> tags to find the .js file reference.

Safari developer tools - reference to .js JavaScript file

  1. Click the link for the .js file.

Safari developer tools - link to .js JavaScript file

  1. The Sources panel is displayed in the developer tool, showing the lines of JavaScript code contained in the .js file. The name of the .js file is also listed at the top of the Sources panel.

Safari developer tools - Sources panel showing JavaScript code

Alexander Pavlov’s answer gets the closest to what you want.

Due to the extensiveness of jQuery’s abstraction and functionality, a lot of hoops have to be jumped in order to get to the meat of the event. I have set up this jsFiddle to demonstrate the work.


1. Setting up the Event Listener Breakpoint

You were close on this one.

  1. Open the Chrome Dev Tools (F12), and go to the Sources tab.
  2. Drill down to Mouse -> Click
    Chrome Dev Tools -> Sources tab -> Mouse -> Click
    (click to zoom)

2. Click the button!

Chrome Dev Tools will pause script execution, and present you with this beautiful entanglement of minified code:

Chrome Dev Tools paused script execution
(click to zoom)


3. Find the glorious code!

Now, the trick here is to not get carried away pressing the key, and keep an eye out on the screen.

  1. Press the F11 key (Step In) until desired source code appears
  2. Source code finally reached
    • In the jsFiddle sample provided above, I had to press F11 108 times before reaching the desired event handler/function
    • Your mileage may vary, depending on the version of jQuery (or framework library) used to bind the events
    • With enough dedication and time, you can find any event handler/function

Desired event handler/function


4. Explanation

I don’t have the exact answer, or explanation as to why jQuery goes through the many layers of abstractions it does – all I can suggest is that it is because of the job it does to abstract away its usage from the browser executing the code.

Here is a jsFiddle with a debug version of jQuery (i.e., not minified). When you look at the code on the first (non-minified) breakpoint, you can see that the code is handling many things:

    // ...snip...

    if ( !(eventHandle = elemData.handle) ) {
        eventHandle = elemData.handle = function( e ) {
            // Discard the second event of a jQuery.event.trigger() and
            // when an event is called after a page has unloaded
            return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
                jQuery.event.dispatch.apply( elem, arguments ) : undefined;
        };
    }

    // ...snip...

The reason I think you missed it on your attempt when the “execution pauses and I jump line by line“, is because you may have used the “Step Over” function, instead of Step In. Here is a StackOverflow answer explaining the differences.

Finally, the reason why your function is not directly bound to the click event handler is because jQuery returns a function that gets bound. jQuery’s function in turn goes through some abstraction layers and checks, and somewhere in there, it executes your function.

24.08.18 ИТ / JavaScript 12128

Иногда при заходе на сайт может возникнуть потребность посмотреть какой JavaScript-код подключен на странице. Это может понадобится в различных ситуациях, например, необходимо разобраться как работает тот или иной функционал на рассматриваемом сайте.

js-get-analize

JavaScript-код может быть внедрен прямо в исходный код страницы сайта, тогда проблем с получением такого кода не возникнет. Но зачастую в добавок к такому коду подключаются и сторонние файлы с кодом, тогда отыскать участок кода, отвечающего за конкретный функционал сложнее. В таком случае необходимо проанализировать, какие файлы подключены на страницу.

Процедура получения кода JavaScript обычно сводится к следующему:

  • открыть исходный код страницы сайта и обратить внимание на подключение скриптов. Обычно скрипты подключаются либо в верхней части страницы, либо внизу – делается это при помощи тега script;
  • скопировать адрес, указанный в атрибуте src тега script;
  • адреса обычно указываются относительные, поэтому далее необходимо подставить в начало к полученному адресу скрипта домен рассматриваемого сайта;
  • после этого достаточно подготовленный адрес вставить в строку адреса браузера в новой вкладке, в результате на странице будет выведен весь код из файла;
  • скопировать код и вставить в редактор с подсветкой синтаксиса.

Данную процедуру можно повторить для каждого подключенного файла, использовав поиск по исходному коду, достаточно указать ключевое слово script.

Когда исходный код получен, можно сделать анализ кода JavaScript:

  • необходимо навести курсор на исследуемый элемент и открыть консоль разработчика при помощи контекстного меню над этим элементом. В консоли следует обратить внимание, какие классы или идентификаторы прописаны у элемента. Получив ключевые слова, можно переходить к следующему пункту;
  • воспользоваться поиском в редакторе с полученным исходным кодом для нахождения нужного участка кода по извлеченным ключевым словам;
  • когда совпадения найдены, можно приступить к изучению участка кода.

При помощи указанной методики, можно получить JavaScript-код практически любой страницы сайта, после чего выполнить комплексный анализ JavaScript-кода. В некоторых случаях анализ кода может быть усложнен, так как может быть применена защита JavaScript-кода, но зачастую такой код никак не защищен.

Время на прочтение
4 мин

Количество просмотров 24K

Чем дальше в лес, тем толще партизаны. Нет, не так. Чем старше веб, тем больше джаваскрипта

Клиентского кода в веб-приложениях с каждым годом действительно становится все больше. Подчас это десятки файлов с сотнями функций. И что делать, когда нам нужно поменять код, выполняемый по событию (например, клик по ссылке). Как его найти? Задавшись решением этой задачи, я придумал несколько разных вариантов. Каждый из них имеет свои плюсы и минусы. И в конце статьи я предлагаю метод, который мне кажется оптимальным.

Формулировка задачи

Сразу скажу, заголовок отражает суть вопроса: мы ищем обработчик события, который был добавлен с использованием библиотеки jQuery, которая сейчас очень популярна. Для демонстрации вариантов решения мы будем использовать Инструменты Разработчика Google Chrome, так как они предоставляют некоторые продвинутые возможности, которых нет в консолях других браузеров. Без этих фишек некоторые варианты решения не представляются возможными вообще.

Подопытный кролик

Искать код обработчика событий мы будем на главной странице Яндекса. Главным образом потому, что он использует jQuery. Не очень новой версии, правда — 1.4, но не суть. В этот раз нас будет интересовать, какой код выполняется при нажатии на ссылку «Сделать Яндекс стартовой страницей». Найти — это значит узнать имя файла скрипта, номер строки. И конечно увидеть сам код.

Метод №1

Используя Инструменты Разработчика Google Chrome (F12), все что нужно сделать — это кликнуть по ссылке правой кнопкой, выбрать «Просмотр кода элемента», щелкнуть по вкладочке «Event Listeners» справа и увидеть там все обработчики событий. Проблема при использовании jQuery в том, что в этом случае этот код будет ничем иным, как куском внутренностей jQuery.

Достоинства

  • в простых случаях это работает

Недостатки

  • если используется jQuery, этот способ малоэффективен
  • если обработчик вешается через live(), то он просто не покажется в списке

Поставим брейкпойнт на событие

Богатый функционал Инструментов Разработчика Google Chrome предоставляет нам возможность ставить брейкпойнты на любые события. Открываем консоль (F12), выбираем вкладку «Scripts», разворачиваем «Event Listener Breakpoint», ставим брейкпойнт на Mouse.click. Кликаем по ссылке, попадаем в какой-то внутренний орган jQuery — скорее всего в ЖКТ. В некоторых случаях этот способ эффективен, и мы сразу можем увидеть вызываемый код. Но только не в этом. Как из этого места добраться до искомого кода — честно говоря, не знаю.

Достоинства

  • иногда срабатывает

Недостатки

  • в этот раз не сработало
  • если обработчиков навешано несколько, мы сможем отловить только первый из них, остальные мы так и не найдем

Если мы что-то знаем

Так случается, что иногда о нужном куске кода мы что-то знаем заранее. Например, по нажатию кнопки она становится другого цвета. В этом случае есть один метод. Щелкаем правой кнопкой на элементе, выбираем «Просмотр кода элемента», кликаем по найденному в иерархии DOM элементу правой кнопкой и выбираем «Break on attributes modifications». Остается только нажать ссылку — и мы попадаем в искомый кусок кода.

Достоинства

  • быстрота получения решения

Недостатки

  • применить можно далеко не всегда, решение не универсально

Используем расширение Chrome

Есть такое замечательное расширение Chrome — Visual Event, которое на первый взгляд творит просто чудеса. Достаточно кликнуть на нужной странице иконку расширения — и для каждого элемента покажутся все обработчики на них навешанные. При наведении на иконку события, можно увидеть выполняемый по событию код.

Достоинства

  • очень просто использовать
  • показывает все, что нужно

Недостатки

  • нужно дополнительно что-то устанавливать
  • на страницах со сложной версткой многие иконки окажутся просто недоступными для просмотра
  • задача все-таки не решается до конца: код-то мы увидели, но в каком файле и на какой строке он находится, мы не знаем

Можно обойтись и без расширения

Тру-хакерам достаточно в консоли Javascript написать $(selector).data(‘events’) и можно увидеть все обработчики, прицепленные к элементу. Если обработчик вешается через live(), то нужно вывести $(document).data(‘events’) и поискать в списке искомый. Однако, как и в случае с расширением, этот метод не решает задачу до конца, и при этом нужно довольно долго искать нужный обработчик.

Наконец-то

Что же предлагаю я как оптимальное решение задачи?

  1. Открываем Инструменты Разработчика Google Chrome (F12), выбираем вкладку «Scripts» и находим в выпадающем списке скрипт jQuery.
  2. Щелкаем кнопочку «Pretty print» для эстетики.
  3. Находим обработчик событий jQuery введя в поиске «handle:». Двоеточие в конце ставится для того, чтобы сразу перейти к объявлению функции. В более новых версиях библиотеки эта функция называется dispatch, но не суть. Эта функция является точкой, через которую проходят все назначенные события. Там хватает кода, нам важна строка, где есть вызов apply — это по сути и есть вызов нашего искомого куска кода.
  4. Событий через функцию проходит много, поэтому ставим не обычный брейкпойнт, а условный. Первым параметром функции является объект события, поэтому пишем «arguments[0].type==’click’».
  5. Кликаем по ссылке и срабатывает брейкпойнт на нашей строчке.
  6. Чтобы перейти к искомому куску кода, жмем «Step into next function call» (F11). Вуаля! Мы не только нашли нужный кусок кода, мы еще и знаем теперь в каком файле и на какой строчке он находится. Задача решена. Прекрасно.
  7. Если обработчиков несколько, последовательно нажимая F8 F11, добираемся до нужного.

Достоинства

  • действительно решает поставленную задачу
  • задача решается стандартными инструментами
  • метод универсальный

Недостатки

  • мозг должен быть включенным

Как найти, в каком файле сайта находится нужен кусок кода?

Смотрю код через консоль браузера. Но не могу найти в каком файле он лежит, чтобы исправить его. Перерыл уже весь сайт. Как сделать, чтобы найти его? Может есть какие-то расширения или плагины?

ТехнологииПрограммирование+3

Добрый день. Возможно тот кусок кода, который вы ищете через консоль в привычном Вам html формате выглядит на сайте в виде кода реализованного через php, что в большинстве случаев и бывает. Надо знать на какой cms вы ищете свой код + что именно вы ищете (код меню, товара или статьи) и посмотреть как реализуют этот код в конкретной cms.

707

Комментировать ответ…Комментировать…

Openstack DevOps and IBM/Informix Certified DBA . Phd in Math (Duality of spaces of…  · 24 июн 2022

Возможный вариант для Linux (Ubuntu,Fedora,AlmaLinux)
Скрипт на bash стартует поиск с каталога передаваемого первым параметром по всем *.py файлам дерева каталогов от старшего.
=======================
`find $1 -name “*.py” -print` передает вывод комманды в переменную shell V.  Далее после 
cat $V | grep “model.add(Dense(3, activation=’softmax’))” проверяется код…
Читать далее

3,7 K

Комментировать ответ…Комментировать…

HTML, CSS, JS, jQuery, MySQL, PHP, Laravel, Vue, Stylus…  · 26 июн 2022

На чем работает сам сайт? На каком движке?

То что вы находите через консоль браузера не всегда найдётся в исходном коде сайта, код может собираться из нескольких файлов, он может строиться JavaScript, сам текст храниться в базе данных или тоже в отдельном файле.

426

Комментировать ответ…Комментировать…

О сообществе

Добавить комментарий