Does JavaScript have a mechanism for determining the line number of the currently executing statement (and if so, what is it)?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
A bit more portable between different browsers and browser versions (should work in Firefox, Chrome and IE10+):
you can use
If your code is javascript + PHP, then the current PHP line number is available in javascript as a literal constant, because it's available in PHP as
<?= __LINE__ ?>
(That's assuming you have PHP short tags enabled, obviously.)
So, for example, in javascript you can say:
However, if you are not careful, the PHP line number might be different from the javascript line number, because PHP "eats" source lines before the browser ever sees them. So the problem becomes ensuring that your PHP and javascript line numbers are the same. If they're different it makes using the browser's javascript debugger a lot less pleasant.
You can ensure the line numbers are the same by including a PHP statement that writes the correct number of newlines needed to synchronize server-side (PHP) and brower-side (javascript) line numbers.
Here's what my code looks like:
The key is this PHP statement:
That's spits out enough newlines to make the line number seen by javascript be the same as the PHP line number. All the PHP function definitions, etc. are at the top, ahead of that line.
After that line, I restrict my use of PHP to code that doesn't change the line numbers.
The "-6" accounts for the fact that my PHP code starts on line 8. If you start your PHP code earlier, you'll reduce that number. Some people put their PHP right at the very top, even ahead of the DOCTYPE.
(The meta viewport line disables Android Chrome "font boosting" per this stackoverflow Q&A: Chrome on android resizes font . Consider it boilerplate, which every web page needs.)
The following line is just for verifying that I haven't made a mistake. Viewed in the browser's debugger, or by right-click / save-web-page, it becomes an HTML comment which shows the correct source file name and line number:
becomes:
Now, wherever I see a line number, whether it's in an error message or in the javascript debugger, it's correct. PHP line numbers and javascript line numbers are always consistent and identical.
you can try:
then throw an error where you want to know (not overly desired, but it might help you if you are debugging.
Note:
window.onerror
isn't defined/handled in WebKit or Opera (last time I checked)You can try to parse a source of a function to seek some marks.
Here is a quick example (yes, it's messed a little).
inject the following snippet to your code: