Главная » Error » Debugging JavaScript issues in Opera

Debugging JavaScript issues in Opera

Typical problems

Most issues Opera-users may encounter on the web falls into the following categories.

Browser blocking

Due to the different standards and levels of JavaScript supported in different browsers nearly every advanced script on the web needs to retrieve information about the browser it is running in. This is called browser sniffing and some webmasters abuse it to block browsers that are unknown or browsers they do not test with.

There is a built-in workaround in Opera: the “Identify as..” setting at the bottom of the F12 “Quick Preferences” menu. This makes Opera disguise itself as another browser and works if the browser sniffing script is not specifically looking for Opera.

The webmaster can usually amend the sniffer script to let Opera in. Opera’s Open The Web project contacts webmasters who block Opera and asks them to consider making their site more accessible and sites that block Opera should be reported to them.

Faulty browser detection causing incompatible commands to be used

This is partly an effect of the “Identify as..” workaround against browser blocking. If a page thinks that Opera is IE or Netscape it may try to use code specific to either browser. This is often a problem with IE-style plugin detection, CSS filters used in JavaScripts or the Netscape-specific syntax document.layers.

Script bugs tolerated in other browsers but not in Opera

Even if a script works fine in IE and is using mostly standards-compliant code it may contain subtle bugs that will cause problems in browsers that are less tolerant of coding mistakes.

Opera bugs

If Opera handles a JavaScript command differently from what the specifications say, it is a bug in Opera. Apparent bugs may also be caused by contradictions in the specifications themselves, or differences between different specifications.

Javascript console for FireFox

Using the code example from the “Diagnosing a JavaScript error” section above, We will find the JavaScript error using Firefox.

  1. Open FireFox.
  2. Go to Tools > Web Developer > Error Console. If you do not have Tools at the top you can use the following shortcut:

    Ctrl + Shift + J

  3. Visit the page with the error. In this case you will see the error on Line 33 in the FireFox Error Console. See image to the right.

The Fix: CORS Attributes and Headers

In order to get visibility into a JavaScript exception thrown by scripts originating from different origins, you must do two things.

1) Add a crossorigin=”anonymous” script attribute

This tells the browser that the target file should be fetched “anonymously.” This means that no potentially user-identifying information like cookies or HTTP credentials will be transmitted by the browser to the server when requesting this file.

2) Add a cross-origin HTTP хедер

Access-Control-Allow-Origin: *

CORS is short for Cross-Origin Resource Sharing, and it’s a set of APIs (mostly HTTP хедерs) that dictate how files ought to be downloaded and served across origins.

By setting Access-Control-Allow-Origin: *, the server is indicating to browsers that any origin can fetch this file. Alternatively, you can restrict it to only a known origin you control:

Access-Control-Allow-Origin: https://www.example.com

Note: most community CDNs properly set an Access-Control-Allow-Origin хедер:

$ curl –head https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.js |
grep -i “access-control-allow-origin”

Access-Control-Allow-Origin: *

Once both of these steps have been made, any errors triggered by this script will report to window.onerror, just like any regular same-domain script. So, instead of “Script error,” the onerror example from the beginning would yield:

“ReferenceError: bar is not defined”, “http://another-domain.com/app.js”, 2, 1, [Object Error]

Boom! You’re done. ”Script error” will plague you and your team no more.

Debugging tools

The JavaScript console

JavaScript error messages are collected in the JavaScript console. They can be reviewed by going to Window > Special > JavaScript console. The section on understanding the JS console output has further details.

Linked scripts bookmarklet

Often, the JavaScript code is not included in the page source but loaded from another file. This bookmarklet generates a convenient list of all the external JavaScript files the currently displayed page uses. To use the bookmarklet, right-click the link below and choose “Add Link to Bookmarks”.
Linked scripts list
On any page where you want an overview of linked scripts, you can open that bookmark.
Notes: will not work if popup windows are completely disabled. If you prefer the Preferences > Window > Re-use existing windows setting disabled you have to drag-and-drop bookmarklets from the Hotlist to the current window to launch the bookmarklet.

A source viewer/editor

If you have not chosen a source viewer, Opera will use MS Wordpad on a typical Windows installation. Many better options are available, this tutorial contains screenshots from SciTE which is a small code editor with support for syntax highlighting, bookmarking specific lines and hiding blocks of code. To tell Opera what program you prefer to use as source viewer, go to Preferences > Programs and paths

The “View > Refresh” command

This is a very powerful tool when debugging a problem because it re-loads the page from cache including any modifications we have made to the locally stored files.

An Alternative Solution: try/catch

Sometimes we’re not in a position to adjust the HTTP хедерs of scripts our web application is consuming. In those situations, there’s an alternative approach: using try/catch.

Consider the original example again, this time with try/catch:

For posterity, some-domain.com/app.js once again looks like this:

// another-domain.com/app.js
function foo() {
bar(); // ReferenceError: bar is not a function
}

Running the example HTML will output the following two entries to the console:

=> ReferenceError: bar is not defined
at foo (http://another-domain.com/b.js:2:3)
at http://example.com/test/:15:3

=> “Script error.”, “”, 0, 0, undefined

The first console statement — from try/catch — managed to get an error object complete with type, message, and stack trace, including file names and line numbers. The second console statement from window.onerror, once again, can only output “Script error.”

Now, does this mean you need to try/catch all of your code? Probably not. If you can easily change your HTML and specify CORS хедерs on your CDNs, it’s preferable to do so and stick to  window.onerror .

But, if you don’t control those resources, using try/catch to wrap third-party code is a surefire (albeit tedious) way to get insight into errors thrown by cross-origin scripts.

Note: by default, raven.js, Sentry’s JavaScript SDK, carefully instruments built-in methods to try to automatically wrap your code in try/catch blocks. It does this to attempt to capture error messages and stack traces from all your scripts, regardless of which origin they’re served from. It’s still recommended to set CORS attributes and хедерs if possible.

Of course, there are plenty of commercial and open-source tools that do all the heavy-lifting of client-side reporting for you. (Psst: you might want to try Sentry for free to debug JavaScript.)

That’s it! Happy error monitoring!

JavaScript library

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Message Routing and Topics: A Thought Shift
  • How to Use MQTT in PHP
  • Microfrontends: Microservices for the Frontend
  • Keep Calm and Respond: A Beginner’s Heuristic to Incident Response

Comments

Javascript console for Chrome

From the “Diagnosing a JavaScript error” section example towards the top, we will find the JavaScript error on a webpage in Google Chrome.

  1. Open Google Chrome.
  2. Click the “Customize and Control Google Chrome” button at the top right side.
  3. From the drop menu, go to Tools > JavaScript console. Or you can press:

    Ctrl + Shift + J

  4. Visit the site with the error. In the Error Console window you will see the error show on line 33. See image to the right.

Diagnosing a JavaScript error

In order to explain how to diagnose a JavaScript error, we will use the simple “pop up” script below (Snapshot to the right shows what it does):


This script simply creates a pop up box that says “I am an alert box!“. We will break the script so that is causes an error by removing one of the quotes like the following.

When the website is ran, the code will break where the quote is missing. The snapshot to the right shows the code that’s broken, and where the lines are in the code.

In this case Line 33 is broken. The methods below will show you how to find the lines of broken code through your browser.

What happens when your JavaScript fails?

If you have JavaScript’s on your site that are not working you can diagnose them by using your browsers “Error Console“. Each browser has a built in “Error Console” for diagnosing scripting errors on your site. Below will show you how to check the “Error Console” in FireFox, Internet Explorer, Chrome, Opera, and Safari.

Javascript console for Internet Explorer

Keep in mind we are using the code example from the “Diagnosing a JavaScript error” section at the beginning of this article. Below is how to use the Error Console in Internet Explorer.

  1. Open Internet Explorer.
  2. Press the function key on your keyboard, F12.
  3. Visit your webpage with the error. You will see the error with the line number of where the error occurs in the document in the bottom Error Console window. The snapshot to the right shows the error on line 33.

I’m Not a Bad Person, Really!

Despite browsers’ good intentions, there are some really good reasons why you want insight into errors thrown from scripts served from different origins:

  1. Your application JavaScript files are served from a different hostname (e.g., static.sentry.io/app.js).
  2. You are using libraries served from a community CDN, like cdnjs or Google’s Hosted Libraries.
  3. You’re working with a commercial third-party JavaScript library that is only served from external servers.

But don’t worry! Getting insight into a JavaScript error served by these files only requires a few simple tweaks.

Understanding the JavaScript console contents

This is the JavaScript Console. It collects the errors happening on all pages during browsing and is a very useful debugging tool.

The console shows information about what went wrong and indicates where the problem was.

Information in the top half of an error message
In this top half of the error message we can see the type of error, line number and detailed information about the problem. If the error occurs in a block the lines are counted from and including the

Javascript console for Opera

Continuing to diagnose the error from “Diagnosing a JavaScript error” section, we will find the JavaScript error on a webpage in Opera.

  1. Open Opera.
  2. Click the Opera button towards the top right.
  3. Navigate to Page > Developer Tools > Error Console. Or you can press the following keyboard keys:

    Ctrl + Shift + O

  4. The Error Console will pop up. You can move the window to the side while you visit your site. You will see the errors list when you visit the site with the broken code. The image to the right shows the error on line 33.

Using our tools

Nothing is like a real-world example. Here we will look at a problem with the main page of the travel agency Opodo.

The problem: no number in departure date box, impossible to make a selection.

After loading Opodo’s UK page we notice an odd absence of numbers in their departure date section. The departure date box goes blank just after the page finishes loading, and since it is impossible to select a departure date the whole site is unusable in Opera. (Snapshot that shows the problem in case Opodo changes their script.)

To understand the problem, we will start looking for error messages and then try to work out what exact part of the script is causing the page to malfunction.

Console analysis

Time to start the debugging in the JavaScript console. Unfortunately the error message is not very rich in details:

Event thread: onload
Error:
name: DOMException
message: INDEX_SIZE_ERR

The error message confirms that there is some problem in the function called from the onLoad event. Let’s use our Source Viewer to inspect the onLoad instruction..

Source review

We invoke the source viewer by selecting View > Source from the menu or by pressing Ctrl+F3. The source of the page will load in the external program and we can search for the onLoad handler.

SciTE source viewer

The function called from onLoad is called “init()”. This means we have to find a block of JavaScript saying something similar to

function init(){
// here goes cryptic code
}

Add debug code

This is where our debug function opera.postError() is handy. By inserting postError statements we can keep track of what the script is doing and where in the init function it stops executing. By editing the cached version in our source viewer we can put in a liberal amount of debug-code:

function init(){
detectLayering();
opera.postError(‘detectLayering OK’); // Debug message
layerPosition();
opera.postError(‘layerPosition OK’); // Debug message
positionErrorLayer();
opera.postError(‘positionErrorLayer OK’); // Debug message
calcDayOfWeek(‘D’);
opera.postError(‘calcDayOfWeek OK’); // Debug message

Refresh Display and view Console output

The output of the debug code

Having edited and saved the code we switch to Opera and use View > Refresh display to make Opera read the changed files, then we check the JavaScript console again to see the output. The console reveals that the message “calcDayOfWeek OK” was never written. Opera stops executing somewhere within the calcDayOfWeek function.

This means we need to locate the definition of calcDayOfWeek to work out what is wrong in this function. This function is not defined in the same file as init but the linked scripts list bookmarklet comes to the rescue and prints out a list of links to all the files Opodo uses. Some searching in the files reveals the function in http://www.opodo.co.uk/js/calendar.js, and we can repeat the strategy of viewing the source and filling the cached version with debug calls:


if((iYear%4==0 && iYear%100!=0)||(iYear%400==0)){
monthDays[1]=29;
} else {
monthDays[1]=28;
}
opera.postError(‘year-aware code OK ‘+monthDays[1]); // Debug message

}
populateDDforThisMonth(sWhich, iYear, iMonth, iDay);
opera.postError(‘populateDD OK’, sWhich, iYear, iMonth, iDay); // Debug message

This also demonstrates how the console reporting command can be used to write out the values of variables while a script is executing. The postError function accepts both a combined string containing variable names and any number of comma-separated arguments. Comma-separated arguments will be written to the console as separate messages.

Viewing the console output shows that script execution stopped before the “populateDD OK” message was written, so the error must be in the populateDDforThisMonth function. By repeating steps 1-5 we can narrow down the “suspects” to another function called emptyDropDown and add our debug code again:

function emptyDropDown(whichDD) {
var oOptions = thisDD.options;
for (var i=oOptions.length; i>=0; i–) {
oOptions[i] = null;
opera.postError(‘loop iteration’+i+’ OK ‘); // Debug message
}
thisDD.selectedIndex=0;
opera.postError(‘thisDD.selectedIndex OK ‘); // Debug message
thisDD.length=0;
opera.postError(‘thisDD.length OK ‘); // Debug message
}

The message “thisDD.selectedIndex OK” is never written to the console, so we can now tell that this statement triggers the error that interrupts the script:

thisDD.selectedIndex=0;

The error occurs because the preceding for (var i=oOptions.length; i>=0; i–) loop deleted all the options in the drop-down. The statement thisDD.selectedIndex=0; means “select the first drop-down element item” but you can not select an option that is already deleted. This is a minor bug in the script that is obviously tolerated by IE but not by Opera. This statement is also entirely superfluous since the script later on set the selectedIndex property to another value after populating the list again.

Opodo’s webmaster can fix the problem by removing the statement. If I want to book a ticket with Opodo using Opera I can now do so by deleting this line, saving the cached version and using View > Refresh Display again in Opera.

Какие вкладки есть в консоли и за что они отвечают

Консоль каждого браузера содержит практически идентичные вкладки с одним и тем же функционалом, поэтому рассмотрим каждый из блоков на примере веб-обозревателя Google Chrome.

Перед тем как перейти к разбору каждой вкладки, давайте рассмотрим основное элементы, которые могут быть полезны при работе с консолью. Первый – это включение адаптивного режима. Для этого необходимо открыть консоль и в верхнем левом углу нажать на кнопку в виде телефона/планшета.

В результате левая часть окна будет немного изменена: добавятся кнопки для выбора разрешения под нужный девайс. Например, выберем устройство iPhone X, и сайт сразу же будет выглядеть так, как он выглядел бы на телефоне.

Как открыть мобильную версию сайта Chrome

Если выбрать опцию «Responsive», то слева от страницы отобразится дополнительная линия, которую мы можем тянуть влево или вправо – с помощью нее можно подобрать необходимое разрешение страницы. Также настроить разрешение мы можем и в верхней части окна.

Как изменить разрешение окна браузера chrome

И еще одна опция, которая может быть полезна – изменение расположения консольной панели. Чтобы ей воспользоваться, необходимо в верхней правой части нажать на кнопку в виде троеточия и в строке «Dock side» изменить ориентацию. Доступные положения: справа, слева, снизу, в отдельном окне.

Как изменить отображение консоли в браузере chrome

На этом стандартный набор функций консольной панели заканчивается. Давайте посмотрим, какие в ней есть вкладки и за что они отвечают.

Elements

Вкладка Elements Chrome

Основной компонент для верстальщиков. Он включает в себя всю информацию об открытой HTML-странице. Здесь мы можем не только посмотреть текущие теги и атрибуты, но и изменить их – в таком случае произойдет автоматическое изменение дизайна на странице. Если ее обновить, все вернется на свои места. Также открыт доступ к просмотру CSS и прочих элементов – для этого в правой части раздела идут вкладки Styles, Computed, Layout, Event Listeners, DOM Breakpoints, Properties и Accessibility.

Console

Вкладка Console в chrome

Еще одна важнейшая вкладка для верстальщиков – это Console. В ней мы можем узнать информацию о текущих ошибках на сайте, посмотреть исполняемый JavaScript-код, если он выведен в консоль с помощью метода console.log, и многое другое. 

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

Как очистить консоль в Chrome

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

Sources

Вкладка Sources chrome

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

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

Network

Вкладка Network в chrome

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

Performance

Вкладка Performance chrome

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

Memory

Вкладка Memory chrome

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

Application

Вкладка Application chrome

Данный раздел позволяет инспектировать и очищать все загруженные ресурсы. Мы можем взаимодействовать с HTML5 Database, Local Storage, Cookies, AppCache и другими элементами.

Основная особенность опции – чистка куки. Если вам необходимо выполнить эту процедуру, то просто откройте в левой части раздел «Cookies» и нажмите справа на значок запрета. Куки для выбранной ссылки будут очищены.

Security

Вкладка security chrome

Раздел Security отображает информацию о безопасном протоколе. Если его нет, то будет сообщено, что данная страница является небезопасной. Кроме того, можно получить еще некоторые сведения о:

  • проверке сертификата – подтвердил ли сайт свою подлинность TLS;
  • tls-соединении – использует ли сайт современные безопасные протоколы;
  • безопасности второстепенных источников.

Lighthouse

Вкладка Lighthouse chrome

Последний раздел представляет собой инструмент аудита с открытым исходным кодом. Благодаря ему разработчики могут повысить производительность и доступность своих веб-сайтов.

The Cause: Cross-Origin Scripts

To better understand what’s going on, consider the following example HTML document, hypothetically served from http://example.com/test:




example.com/test


Here’s the contents of http://another-domain.com/app.js. It declares a single function, foo, whose invocation will always throw a ReferenceError.

// another-domain.com/app.js
function foo() {
bar(); // ReferenceError: bar is not a function
}

When this document is loaded in the browser, and JavaScript is executed, the following is output to the console (logged via the window.onerror  callback):

“Script error.”, “”, 0, 0, undefined

This isn’t a JavaScript bug — browsers intentionally hide errors originating from script files from different origins for security reasons. It’s to avoid a script unintentionally leaking potentially sensitive information to an onerror callback that it doesn’t control. For this reason, browsers only give window.onerror insight into errors originating from the same domain. All we know is that an error occurred — nothing else!

Источники

  • http://www.hallvord.com/opera/jsdebug.htm
  • https://www.inmotionhosting.com/support/website/error-numbers/diagnose-javascript-errors/
  • https://dzone.com/articles/what-the-heck-is-script-error
  • https://timeweb.com/ru/community/articles/kak-ispolzovat-konsol-brauzera-dlya-vyyavleniya-oshibok
[свернуть]
Решите Вашу проблему!


×
Adblock
detector