Как остановить javascript в браузере хром
How can I exit the JavaScript script much like PHP's exit or die ? I know it's not the best programming practice but I need to.
The question is very simple and clear: it says "terminate the script". This means that the script is over. Finished. No more things should be expected to happen after that. It doesn't mean just "terminate a function". A return from a function (as suggested here) is not a solution because there may follow other things that will occur after that and the programmer wants to cancel them! I think it's very simple
24 Answers 24
"exit" functions usually quit the program or script along with an error message as paramete. For example die(. ) in php
The equivalent in JS is to signal an error with the throw keyword like this:
You can easily test this:
@Sydwell : If you surround it by catch block, it will be caught and the program won't terminate, defying the point here.
Don't forget that you can add a message to the error: throw new Error('variable ='+x); It's a nice way to quickly end a script while you're working on it and get the value of a variable.
That code doesn't appear to stop events on elements from firing, just the window's events. So you'd also need to loop through all the elements on the page doing something similar. It all sounds like a very odd requirement though.
the whole die concept is a bit broken - the flow should be capable of handling any and all eventualities, whether that reqire try-catch or not.
why does javascript need such convoluted hacks for basic, basic functionality that should just exist?
Even in simple programs without handles, events and such, it is best to put code in a main function, even when it is the only procedure :
This way, when you want to stop the program you can use return .
Works if you're a poor programmer and don't break your code into other functions. If you do, then a return inside a function that's inside a function won't do what you want.
If you don't care that it's an error just write:
That will stop your main (global) code from proceeding. Useful for some aspects of debugging/testing.
yes it could be helpful for people to know that you're just forcing a ReferenceError by calling an undefined variable
For debugging purposes (because otherwise you don't care), if one is to exit in a quick and "dirty" way, then better show a (recognizable) message with throw(message)
There are many ways to exit a JS or Node script. Here are the most relevant:
If you're in the REPL (i.e. after running node on the command line), you can type .exit to exit.
I didn't want to insult the intelligence of the readers by explaining an acronym that shows up as the first result of Googling it. I suggest you don't mix JavaScript code with REPL commands because if a user copy/pastes that code block and runs it, they'll get a Syntax error on the ".exit" line.
Place the debugger; keyword in your JavaScript code where you want to stop the execution. Then open your favorite browser's developer tools and reload the page. Now it should pause automatically. Open the Sources section of your tools: the debugger; keyword is highlighted and you have the option to resume script execution.
I hope it helps.
More information at:
In my case I used window.stop .
The window.stop() stops further resource loading in the current browsing context, equivalent to the 'stop' button in the browser.
Because of how scripts are executed, this method cannot interrupt its parent document's loading, but it will stop its images, new windows, and other still-loading objects.
Usage: window.stop();
(source)
Javascript can be disabled in devtools: ctrl+shift+j followed cltf+shift+p then type disable javascript
Possible options that mentioned above:
If page is loaded and you don't want to debug crash or reload:
Additionally clear all timeouts
this removes scripts and recreates elements without events
If jQuery is not available on the webpage copy-paste source code into a console.
There're might be other stuff. Let me know in a comment.
I think this question has been answered, click here for more information. Below is the short answer it is posted.
You can also used your browser to add break points, every browser is similar, check info below for your browser.
For Chrome break points info click here
For Firefox break points info click here
For Explorer break points info click
For Safari break points info click here
In JavaScript multiple ways are there, below are some of them
Method 1:
Method 2:
Method 3:
Method 4:
Method 5:
write your custom function use above method and call where you needed
Note: If you want to just pause the code execution you can use
If you're looking for a way to forcibly terminate execution of all Javascript on a page, I'm not sure there is an officially sanctioned way to do that - it seems like the kind of thing that might be a security risk (although to be honest, I can't think of how it would be off the top of my head). Normally in Javascript when you want your code to stop running, you just return from whatever function is executing. (The return statement is optional if it's the last thing in the function and the function shouldn't return a value) If there's some reason returning isn't good enough for you, you should probably edit more detail into the question as to why you think you need it and perhaps someone can offer an alternate solution.
Note that in practice, most browsers' Javascript interpreters will simply stop running the current script if they encounter an error. So you can do something like accessing an attribute of an unset variable:
and it will probably abort the script. But you shouldn't count on that because it's not at all standard, and it really seems like a terrible practice.
EDIT: OK, maybe this wasn't such a good answer in light of Ólafur's. Although the die() function he linked to basically implements my second paragraph, i.e. it just throws an error.
Давайте отвлечёмся от написания кода и поговорим о его отладке.
Отладка – это процесс поиска и исправления ошибок в скрипте. Все современные браузеры и большинство других сред разработки поддерживают инструменты для отладки – специальный графический интерфейс, который сильно упрощает отладку. Он также позволяет по шагам отследить, что именно происходит в нашем коде.
Мы будем использовать браузер Chrome, так как у него достаточно возможностей, в большинстве других браузеров процесс будет схожим.
Панель «Исходный код» («Sources»)
Версия Chrome, установленная у вас, может выглядеть немного иначе, однако принципиальных отличий не будет.
- Работая в Chrome, откройте тестовую страницу.
- Включите инструменты разработчика, нажав F12 (Mac: Cmd + Opt + I ).
- Щёлкните по панели Sources («исходный код»).
При первом запуске получаем следующее:
Кнопка-переключатель откроет вкладку со списком файлов.
Кликните на неё и выберите hello.js в дереве файлов. Вот что появится:
Интерфейс состоит из трёх зон:
- В зоне File Navigator (панель для навигации файлов) показаны файлы HTML, JavaScript, CSS, включая изображения, используемые на странице. Здесь также могут быть файлы различных расширений Chrome.
- Зона Code Editor (редактор кода) показывает исходный код.
- Наконец, зона JavaScript Debugging (панель отладки JavaScript) отведена для отладки, скоро мы к ней вернёмся.
Чтобы скрыть список ресурсов и освободить экранное место для исходного кода, щёлкните по тому же переключателю .
Консоль
При нажатии на клавишу Esc в нижней части экрана вызывается консоль, где можно вводить команды и выполнять их клавишей Enter .
Результат выполнения инструкций сразу же отображается в консоли.
Например, результатом 1+2 будет 3 , а вызов функции hello("debugger") ничего не возвращает, так что результатом будет undefined :
Точки останова (breakpoints)
Давайте разберёмся, как работает код нашей тестовой страницы. В файле hello.js щёлкните на номере строки 4 . Да-да, щёлкайте именно по самой цифре, не по коду.
Ура! Вы поставили точку останова. А теперь щёлкните по цифре 8 на восьмой линии.
Вот что в итоге должно получиться (синим это те места, по которым вы должны щёлкнуть):
Точка останова – это участок кода, где отладчик автоматически приостановит исполнение JavaScript.
Пока исполнение поставлено «на паузу», мы можем просмотреть текущие значения переменных, выполнить команды в консоли, другими словами, выполнить отладку кода.
В правой части графического интерфейса мы видим список точек останова. А когда таких точек выставлено много, да ещё и в разных файлах, этот список поможет эффективно ими управлять:
- Быстро перейдите к точке останова в коде (нажав на неё на правой панели).
- Временно отключите точку останова, сняв с неё галочку.
- Удалите точку останова, щёлкнув правой кнопкой мыши и выбрав Remove (Удалить).
- …и так далее.
Щелчок правой кнопкой мыши по номеру строки позволяет создать условную точку останова. Она сработает только в тот момент, когда выражение, которое вы должны указать при создании такой точки, истинно.
Это удобно, когда нам нужно остановиться только для при определённом значении переменной или для определённых параметров функции.
Команда debugger
Выполнение кода можно также приостановить с помощью команды debugger прямо изнутри самого кода:
Такая команда сработает только если открыты инструменты разработки, иначе браузер ее проигнорирует.
Остановимся и оглядимся
В нашем примере функция hello() вызывается во время загрузки страницы, поэтому для начала отладки (после того, как мы поставили точки останова) проще всего её перезагрузить. Нажмите F5 (Windows, Linux) или Cmd + R (Mac).
Выполнение прервётся на четвёртой строчке (где находится точка останова):
Чтобы понять, что происходит в коде, щёлкните по стрелочкам справа:
Watch – показывает текущие значения для любых выражений.
Вы можете нажать на + и ввести выражение. Отладчик покажет его значение, автоматически пересчитывая его в процессе выполнения.
Call Stack – показывает цепочку вложенных вызовов.
В текущий момент отладчик находится внутри вызова hello() , вызываемого скриптом в index.html (там нет функции, поэтому она называется “анонимной”).
Если вы нажмёте на элемент стека (например, «anonymous»), отладчик перейдёт к соответствующему коду, и нам представляется возможность его проанализировать.
Scope показывает текущие переменные.
Local показывает локальные переменные функций, а их значения подсвечены прямо в исходном коде.
В Global перечисляются глобальные переменные (то есть вне каких-либо функций).
Там также есть ключевое слово this , которое мы ещё не изучали, но скоро изучим.
Пошаговое выполнение скрипта
А теперь давайте пошагаем по нашему скрипту.
Для этого есть кнопки в верхней части правой панели. Давайте рассмотрим их.
– «Resume»: продолжить выполнение, быстрая клавиша F8 .
Возобновляет выполнение кода. Если больше нет точек останова, то выполнение просто продолжается, без контроля отладчиком.
Вот, что мы увидим, кликнув на неё:
Выполнение кода возобновилось, дошло до другой точки останова внутри say() , и отладчик снова приостановил выполнение. Обратите внимание на пункт «Call stack» справа: в списке появился ещё один вызов. Сейчас мы внутри say() .
– «Step»: выполнить следующую команду, быстрая клавиша F9 .
Выполняет следующую инструкцию. Если мы нажмём на неё сейчас, появится alert .
Нажатие на эту кнопку снова и снова приведёт к пошаговому выполнению всех инструкций скрипта одного за другим.
– «Step over»: выполнить следующую команду, но не заходя внутрь функции, быстрая клавиша F10 .
Работает аналогично предыдущей команде «Step», но ведёт себя по-другому, если следующая инструкция является вызовом функции (имеется ввиду: не встроенная, как alert , а объявленная нами функция).
Если сравнить, то команда «Step» переходит во вложенный вызов функцию и приостанавливает выполнение в первой строке, в то время как «Step over» выполняет вызов вложенной функции незаметно для нас, пропуская её внутренний код.
Затем выполнение приостанавливается сразу после вызова функции.
Это хорошо, если нам не интересно видеть, что происходит внутри вызова функции.
– «Step into», быстрая клавиша F11 .
Это похоже на «Step», но ведёт себя по-другому в случае асинхронных вызовов функций. Если вы только начинаете изучать JavaScript, то можете не обращать внимания на разницу, так как у нас ещё нет асинхронных вызовов.
На будущее просто помните, что команда «Step» игнорирует асинхронные действия, такие как setTimeout (вызов функции по расписанию), которые выполняются позже. «Step into» входит в их код, ожидая их, если это необходимо. См. DevTools manual для получения более подробной информации.
– «Step out»: продолжить выполнение до завершения текущей функции, быстрая клавиша Shift + F11 .
Продолжает выполнение и останавливает его в самой последней строке текущей функции. Это удобно, когда мы случайно вошли во вложенный вызов, используя , но это нас не интересует, и мы хотим продолжить его до конца как можно скорее.
– активировать/деактивировать все точки останова(breakpoints).
Эта кнопка не влияет на выполнение кода, она лишь позволяет массово включить/отключить точки останова.
– включить/отключить автоматическую паузу в случае ошибки.
При включении, если открыты инструменты разработчика, ошибка при выполнении скрипта автоматически приостанавливает его. Затем мы можем проанализировать переменные в отладчике, чтобы понять, что пошло не так. Поэтому, если наш скрипт умирает с ошибкой, мы можем открыть отладчик, включить эту опцию и перезагрузить страницу, чтобы увидеть, где он умирает и каков контекст в этот момент.
Щелчок правой кнопкой мыши по строке кода открывает контекстное меню с отличной опцией под названием «Continue to here» («продолжить до этого места»).
Это удобно, когда мы хотим перейти на несколько шагов вперёд к строке, но лень устанавливать точку останова (breakpoint).
Логирование
Чтобы вывести что-то на консоль из нашего кода, существует функция console.log .
When stepping through JavaScript code in Google Chrome debugger, how do I terminate script execution if I do not want to continue? The only way I found is closing the browser window.
Pressing "Reload this page" runs the rest of the code and even submits forms as if pressing F8 "Continue".
UPDATE:
When pressing F5 (Refresh) while a script is paused:
- Google Chrome (v22) runs the script. If the script submits HTTP request, the HTTP response for that request is displayed. The original page is not refreshed.
- IE 9 just freezes. However IE has an option "Stop Debugging" which, when pressed (provided you did not press F5 earlier), continues to run the script outside debugger.
- Firebug behaves identically to Chrome.
Closing and then opening again the browser window is not always the next easiest way because it will kill browser session state and that may be important. All your breakpoints are also lost.
UPDATE (Jan 2014):
Refresh while debugging:
- Chrome v31: lets scripts to run and stops on further breakpoints (but does not submit ajax requests), then refreshes.
- IE 11: refresh does nothing, but you can press F5 to continue.
- Firefox v26: lets scripts to run but does not stop on further breakpoints, submits ajax requests, then refreshes.
Kind of progress!
Navigate to the same page while debugging:
- Chrome v31: same as Refresh.
- IE 11: scripts are terminated, new browser session is started (same as closing and opening again).
- Firefox v26: nothing happens.
Also juacala suggested an effective workaround. For example, if you are using jQuery, running delete $ from console will stop execution once any jQuery method is encountered. I have tested it in all above browsers and can confirm it is working.
UPDATE (Mar 2015):
Finally, after over 2 years and almost 10K views, the right answer was given by Alexander K. Google Chrome has its own Task Manager which can kill a tab process without closing the tab itself, keeping all the breakpoints and other stuff intact.
Juacala's workaround is still useful when debugging in IE or Firefox.
UPDATE (Jan 2019):
Chrome Dev Tools at last added a proper way to stop script execution which is nice (although a bit hidden). Refer to James Gentes's answer for details.
I am trying to debug the features of a website when users disable their JavaScript. I was wondering how do you disable JavaScript for a page from the Google Chrome DevTools?
I am adding this as a comment because it does not answer the OP question, but it answers a related question that I was looking for (I found this, but not an answer to my question). If you want to turn off only a specific script, for example a slide show, because it is impeding efforts of adjusting CSS styles in Dev tools, do the following: Go Sources tab. Navigate file tree to find the script (usually you want to choose the minimized version). Click the || pause button. Now you can go back to the Elements tab to inspect/edit CSS without HTML (& scroll location) constantly changing.
21 Answers 21
Click the gear icon in the corner of the Developer Tools, click Settings , then under Debugger , check Disable Javascript , as shown in the following video:
@PaintyJoy, thanks for that tip. For some reason my "Disable Javascript" is being buggy when I refresh. "Incognito Mode" -> F12 > Settings > "Disable Javascript" -> Refresh works! Would love to know WHY it's not working in regular mode. I haven't found any tickets for this issue. Seems to only happen to certain users.
Can you please add a screenshot that shows the location of the "gear" icon in the lower-right corner of the Developer Tools? For example, here is a screenshot of the Developer Tools that shows there is no "gear" icon.
You will now find the "Disable JavaScript" option on the right side in de Preferences menu. Headline is: "Debugger"
Update August 2020
- Developer Tools (F12)
- Click the Gear icon
- Should open the Preference tab
- Disable Javascript option is on the far right
Original answer
- Developer Tools (F12)
- Three vertical dots in upper right
- Settings
- Under the "Preferences" tab on the left
- There will be a "Debugger" section with the option (probably on far right)
Maybe it's less important now so many web apps require JavaScript? It's so frustrating because I have to keep testing graceful degradation so I need to continually switch back and forth.
There's now a command menu built into DevTools that makes it easier to disable JavaScript. This has been around as of April 2016 or so.
-
.
- Press Command + Shift + P (Mac) or Control + Shift + P (Windows, Linux) to open the Command Menu. Make sure that your cursor's focus is on the DevTools window, not your browser viewport.
- Type Disable JavaScript (or some version of that. it's a fuzzy search) and then press Enter .
Use the Enable JavaScript command when you want to turn it back on.
chrome://settings/content Javascript/Manage Exceptions
This extension makes it faster (I am the author) : Quick Javascript Switcher
You can also run Chrome with JavaScript disabled by default by using the flag:
You would use this for example by running Chrome like this:
The quickest way is problably this one:
- F12 to open the dev console
- ctrl + shift + p to open the command tool (windows)
- Type 'disable javascript' and hit enter
On OSX, I had to click the triple vertical dots, and uncheck a box in the settings section. Which can also be opened with f1
Using only the keyboard at least for Windows 10:
- F12 , shows Developer Tools
- F1 , shows Settings
- tab , moves to the "Disable Javascript" check box
- space , toggles the option
- esc , hides Settings
- Preferences
- Show advanced settings
- Press the "content settings" button
- Scroll to the "JavaScript" section
- Check the checkbox in front of "Do not allow any site to run JavaScript"
- Go to options (Windows: three vertical dots in the top right) -> Settings, or hit F1.
- In the General section you find "disable JavaScript"
The gear icon is no longer part of developer tools. Since Chome 30.0 it is not even possible to bring it back (In Google Chrome Developer Tools, the toolbar icons disappeared. What gives?)
To temporarily block JavaScript on a domain :
- Click on the Button left to the address on the address bar (which says View site information )
- In the drop-down next to JavaScript , select Always block on this site
- Reload Page
- Click the ⋮ menu in the corner of the Developer Tools, click Settings
- Click on Advanced at the bottom
- Click on Content Settings
- Click on JavaScript
- Switch off
The fast way:
1) just click on CTRL + SHIFT + P
2) fill the field by the 3 letters dis and will appear this box and select the item Disable Javascript
that's all folks!
Full and fast instructions for Chrome browsers (Opera incl.)
The first way
- If Developer Tools aren't open then press F12 key on keyboard to show the Developer Tools. In Opera browser you have to use key combination Ctrl + Shift + i on keyboard to open it.
- To show the settings just press F1 key on keyboard. The Developer Tools window must be focused when you are doing it. Or if you want to open the settings with the mouse then you have to click on ⋮ button in the top right corner of the Developer Tools, then click Settings in the menu.
Then you have to scroll down the settings window to bottom and then you will see the checkbox for disabling JavaScript like follows:
Just click on this checkbox and push esc key on keyboard for hide the settings. If you want to enable it then you have to do the same way again.
The second way
- If Developer Tools aren't open then open it like in the first way is described.
- Press the key combination Ctrl + Shift + P (for Windows or Linux) or Cmd (⌘) + Shift + P (for Mac) to open the Command Menu. Be sure that the focus is on the DevTools window.
- Type there "Disable JavaScript" and then press Enter or click it with the mouse. If you want to turn back the enanled JS then open the Command Menu again and type there "Enable JavaScript" and then press Enter or click it with the mouse. You could also write just only "JavaScript" or "Java" there and then choose it with the mouse.
If all this does not work
For some reason it is possible that it does not work. I this case open a new empty site in "Incognito Mode" and do all this there.
The quickest way
In Chrome Web Store or on Opera Addon site you can find and install extensions which do it per one click. Just search "Javascript Switcher" :
Многие задают мне один и тот же вопрос:
«Как дебажить этот $%*!%$! JavaScript?».
Так вот, во-первых JavaScript — не $%*!%$! А как я его дебажу — сейчас расскажу.
(Примечание: наверное эта статья больше для новичков. Так что не судите строго)
Казалось бы — да что тут рассказывать? Всё же очевидно. Но вопрос этот мне задают с завидной частотой. Да и мне есть, что рассказать.
Приведу конкретные примеры и расскажу, как я их решаю.
Видим цель, не видим препятствий
JavaScript вывалил ошибку? Замечательно! Нет, это конечно плохо, но гораздо лучше, чем если бы он промолчал (да, бывает и такое!) в случае ошибки.
Наша цель — понять, что же, чёрт побери, произошло? Но сначала — рекламная пауза лирическое отступление: средства JavaScript Debug'а в основных браузерах.
Debuggers
А вот немного «вкусностей» — conditional breakpoints (правый клик по «бряке»):
То есть заводим глобальную переменную (к примеру) allowBreakpoints и «бряки» будут срабатывать только тогда, когда мы сами того захотим.
К сожалению, работает не везде, поэтому я это обычно не использую.
Как «тормознуть» поток
Ключевое слово debugger . Увидав такое в коде, любой уважающий себя JS-debugger остановит поток JavaScript и покажет нам место остановки
А вот вариант с условной остановкой:
* This source code was highlighted with Source Code Highlighter .
Мне так нравится гораздо больше, чем ставить «бряку»: так я пишу код и дебажу его по сути в одном месте, а не в двух.
Debug через alert()
Это наименее информативный debug, который к тому же останавливает поток JavaScript. Да к тому же модальный по отношению к браузеру. Забудьте, что он вообще существует.
Особенность breakpoint'ов
Рассмотренные варианты все, как один, тормозят поток JavaScript. Это плохо!
Почему? Если в момент остановки скрипта у вас был запущен AJAX-запрос или Timeout, и ответ не успел вернутся — он может уже не вернутся никогда. Согласитесь, в современных web-проектах этого добра хватает. Поэтому в момент «экстренной остановки» скрипта мы уже не сможем адекватно debug'ать дальше — часть логики будет безвозвратно утеряна.
Поэтому я стараюсь избегать на практике debug с остановкой.
Однако: breakpoint есть breakpoint, и если вы исследуете ну очень запущенный баг — тут без остановки не обойтись (надо будет сделать watch текущим переменным и т.д.)
«Правильный» debug
Коротко: хороший debug — через logging. Так я в основном и работаю — в нужном месте в нужное время срабатывает console.log(. ) .
Да, насчёт console.log — впервые этот метод увидел мир, насколько я помню, вместе с Firebug. Никакой это не стандарт и не факт, что оно заработает в IE6. Однако современные браузеры вводят logging именно как console.log . Это так, к сведению. И если в продакшн попадёт код с console.log(. ) — будьте на чеку, может поломаться! Так что может быть стоит переопределить у себя в коде объект console , так, на всякий пожарный.
Если же в целевом браузере нет console.log , а хочется — попробуйте Firebug Lite или Blackbird, может понравится ;)
Пример №1
JavaScript показал ошибку. Надо понять — что к чему.
Включаем в debugger'е режим «Break On Error»:
Воспроизводим ошибку снова. JavaScript останавливается. Видим место ошибки, делаем watch и точно определяем, в чём же дело.
Пример №2
CASE:
JavaScript не показал ошибку. Но вы знаете, что она есть (как суслик). Да, такое иногда бывает.
CASE:
Надо просто продебажить некий код. Скажем, посмотреть, что происходит по нажатию кнопки или после AJAX-загрузки данных.
Тут сложней — надо найти, с чего начать.
Немного искусства
- Самое главное — разбираться в средстве разработки. Будь то jQuery, или ExtJS, или Mootools, или вообще свой собственный framework — нужно понимать, как создаётся кнопка, как «навешивается» обработчик события, как данные ходят в AJAX, как попадают в grid, как работает TinyMCE RTE, как, как, как… Если нет понимания задачи — не получится её решить!
- Используем Inspect нашего debugger'а (если нет Inspect'а — используйте всё тот же Firebug Lite):
- Находим нужный элемент HTML (например, кнопку)
- Ищем ближайший от него элементс осмысленным ID (н-р: а уже не подходит) вверх по иерархии (это может быть и сама кнопка, а может быть DIV четырмя уровнями выше)
// условная остановка
if (allowBreakpoints == true )
debugger;// или просто
debugger;
* This source code was highlighted with Source Code Highlighter .Так, значит место в коде нашли, бряку поставили. Если не хочется (или просто нельзя) изменять исходный код — можно вместо ключевого слова debugger поставить brakepoint в средстве отладки.
Пример №3
Тот же случай: надо продебажить некий код. Скажем, посмотреть, что происходит по нажатию кнопки или после AJAX-загрузки данных. Но в этот раз мы не можем тормозить поток JavaScript по описанным мной причинам.
- Ищем нужное место тем же способом
- Вместо debugger пишем console.log(variable_to_watch)
CASE UNO
variable_to_watch — объект, который изменился с момента вывода в консоль. А хочется увидить его состояние именно на момент вызова.
Тут надо использовать не console.log(variable_to_watch) , а console.dir(variable_to_watch)
CASE DUO
Нужно не просто увидеть текущее значение variable_to_watch , но ещё и поэкспериментировать с ним (например, хочется вызвать его метод):// пусть хочется получить доступ к объекту obj
if (debugEnabled)
console.log(window.temp_var = obj);
* This source code was highlighted with Source Code Highlighter .Таким образом мы не только увидим вывод в консоли, но и получим доступ к объекту через глобальную ссылку на него: window.temp_var .
Открываем Firebug->Console и вызваем метод: temp_var.objMethod() .
Нет консоли? Пишем в адресной строке: javascript:alert(temp_var.objMethod()); void 0;
Пример №4
Ещё один пример. Возможно, немного странный. Хочется продебажить метод 3d-party-framework'а (например, ExtJS), но вот беда — нельзя тормозить JavaScript и нет доступа к исходному коду (правда странный пример? :)
Что же делать? Я делаю так:
Создаём файл с патчем: my-ext-patch.js, и подключаем его после ext-all.js
Внутри пишем что-то вроде:( function () var _backup = Ext.form.Form.render; // Резервируем метод рендера формы. -- Ваш Кэп ;)
Ext.form.Form.render = function (container) < // Wrap'им метод
// А вот и дебаг
console.log(container);// Возможны варианты:
// console.dir(container);
// console.log(window.t = container);
// debugger;// Выполняем начальный метод
return _backup.apply( this , arguments);
>
>)();
* This source code was highlighted with Source Code Highlighter .Извращение? Возможно. Но мне нравится >:)
Эпилог
Вот так можно дебажить
«этот $%*!%$!»JavaScript. Важно сосредоточиться на первых трёх примерах.Читайте также: