How to detect javascript

How to detect if script is running in browser or in Node.js? [duplicate]

I have jasmine test spec file and I want to run it using both node.js and in browser. How can I detect if script is running in node?

@CiroSantilli郝海东冠状病六四事件法轮功 it was asked 5 years ago but I think this is better answer, the solution looks beter.

Hi there, date does not matter much BTW, I just go by question upvotes since it is so hard to decide answer quality. Answers can be migrated if not covered on the other question.

3 Answers 3

You can check for the window global object, if it is available then you are in a browser

if (typeof window === 'undefined') // this is node 

Or you can check for the process object, if it is available then you are in node

if(typeof process === 'object') // this is also node 

I found that many proposed solutions stop working if the code has been webpack’d, because webpack defines all kinds of process , module , require , etc symbols. window usually still works, unless of course you additionally also want to detect being run from a webworker, where there is no window .

the check on window will not worker inside a WebWorker . 🙂 however, the check against process will work canonically in all environments afaiu

another idea, to avoid checking on process in the browser: the global var self is an alternative to using window (but is equivalent to it in main thread) and refers to the global worker scope otherwise.

As of 2021, Firefox browser has an object on the root called process , so the second method doesn’t work unless you also check for the title attribute like this; typeof process === ‘object’ && process.title === ‘node’

Источник

How to detect if javascript is executing on page

Is there a way to detect if javascript is executing a script using either JQuery, javascript, WebDriver, or C# (like a browser API or something)? For example, say I’m on a webpage and I just selected a U.S. State (let’s say California) from a picklist, and some javascript is now loading a second picklist with all the cities found in California. How can I detect if javascript is executing, and when it has finished? I’m running into problems with WebDriver since it doesn’t know how to wait for a script to stop executing aside from pausing for a few seconds.

5 Answers 5

you can create a callback function, when the call for the picklist ends it triggers the callback.

I’m afraid I need something a little more generalized; I don’t have access to the code base to be able to add callback functions. I can execute javascript/jquery with WebDriver, but that’s about it.

Your question could be taken several ways.

Are you trying to see if javascript is enabled on the browser from your server-side code? I have done this by sending a small page with a form field and some javascript to populate that field and post-back. if the post-back doesn’t happen, the page says something about ‘javascript must be enabled.’ If it DOES postback, I know Javascript is enabled.

Читайте также:  Java compress to gzip

If you’re are client-side and you need to wait for something to complete, like loading your US State pull-down you need to wire up on-completion type events. Browsers are asynchronous by nature (that’s a good thing) so you need to ‘register’ callbacks for key things to know when they’ve completed.

Without specific markup or situations it’s tough to offer more.

I don’t particularly care if javascript is enabled or not, just whether it’s currently running a script or not. I need to be able to detect if javascript is running on a very general basis, perhaps in a function like IsJavascriptCurrentlyDoingSomething().

Wouldn’t IsJavascriptCurrentlyDoingSomething() return true because IsJavascriptCurrentlyDoingSomething() is running?

LOL, I suppose it would. I think that’s my answer right there — unless I can bind to a «javascriptIsRunning» event (which doesn’t exist), then what I’m asking for isn’t possible..

Marking as accepted answer, thanks for your responses everyone, you’ve given some great insight that has been very helpful to me!

Источник

How to detect if javascript files are loaded?

Is there an event that fires when JavaScript files are loaded? The problem came up because YSlow recommends to move JavaScript files to the bottom of the page. This means that $(document).ready(function1) is fired before the js file that contains the code for function1 is loaded. How to avoid this kind of situation?

7 Answers 7

I don’t have a reference for it handy, but script tags are processed in order, and so if you put your $(document).ready(function1) in a script tag after the script tags that define function1, etc., you should be good to go.

Of course, another approach would be to ensure that you’re using only one script tag, in total, by combining files as part of your build process. (Unless you’re loading the other ones from a CDN somewhere.) That will also help improve the perceived speed of your page.

EDIT: Just realized that I didn’t actually answer your question: I don’t think there’s a cross-browser event that’s fired, no. There is if you work hard enough, see below. You can test for symbols and use setTimeout to reschedule:

  

. but you shouldn’t have to do that if you get your script tag order correct.

Update: You can get load notifications for script elements you add to the page dynamically if you like. To get broad browser support, you have to do two different things, but as a combined technique this works:

function loadScript(path, callback) < var done = false; var scr = document.createElement('script'); scr.onload = handleLoad; scr.onreadystatechange = handleReadyStateChange; scr.onerror = handleError; scr.src = path; document.body.appendChild(scr); function handleLoad() < if (!done) < done = true; callback(path, "ok"); >> function handleReadyStateChange() < var state; if (!done) < state = scr.readyState; if (state === "complete") < handleLoad(); >> > function handleError() < if (!done) < done = true; callback(path, "error"); >> > 

In my experience, error notification ( onerror ) is not 100% cross-browser reliable. Also note that some browsers will do both mechanisms, hence the done variable to avoid duplicate notifications.

Источник

How can a site instantly detect that javascript has been disabled?

Normally, when a page is loaded, and the browser has Javascript disabled, we use the

Читайте также:  How to make methods in java

What I have tried

I thought about having a segment inside my page which keeps checking if Javascript is disabled, if yes, show the contents of

This page will keep on refreshing, when JS is disabled, JS is disabled! will appear. To add this page inside my original page. I tried the following: 1- .load() I used JQuery to .load(‘CheckJS.html’) inside a div . However, it seems that .load() only loads the contents of the of CheckJS.html. Means the element and what’s inside it will not be loaded inside the div . 2- iframe After some searching, I found that the only possible way to load a FULL html page including is to use an .

However, the of CheckJS.html affects the parent page, the original page itself started refreshing. If we are able to use this without forcing the original page to refresh, then this could be a solution, but even if this solution is found, I feel its more of a trick rather than a real solution. UPDATE Antony ‘s answer proved that I was wrong about that the iframe refreshes the original page, the browser shows that its refreshing but actually its not, if this is it, then Javascript can be avoided, the CheckJS.html that I provided does the job, and even better, the will be hidden when JS is re-enabled. Still this whole iframe approach isn’t so user friendly (could freeze the browser), unless refresh occurs every 10 seconds or so, which isn’t an instant detection.

Источник

How to detect JS frameworks/libraries used in a page?

I’d like to be able to detect all the frameworks/libraries used by a page, to help understand when content is dynamically-generated etc. I downloaded and unpacked the source for two Chrome extensions, Library Detector and Appspector. It looks like they simply call window.FUNCTION_NAME_HERE , for example:

'Backbone.js': function () < return window.Backbone && typeof(window.Backbone.sync) === 'function'; >, 'Underscore.js': function () < return window._ && typeof(window._.identity) === 'function' && window._.identity('abc') === 'abc'; >, 'Spine': function () < return window.Spine; >, 'Angular': function () < return window.angular; >, 'Ning': function () < return window.ning; >, 'Zepto': function ()
  1. What are the identifiers for each framework (e.g. «Spine», «angular») called? Is there any way to retrieve this information via AJAX or otherwise, so I don’t have to manually enter them?
  2. I don’t really understand what window.angular means, besides that it returns either the angular object or None. I know that AngularJS has loaded if the angular function is accessible through the window object, but I’m not really sure what it even means to be a member function of the window.
  3. Why is the procedure for Backbone and Underscore different than all the others? How do you know which one to use?
  4. I tried running both extensions on the Uber homepage, which uses React, and neither of them detected React. When I tried to console.log(window) , there wasn’t a React object listed either. Why is this, and how can I still detect the framework in these cases?

Your code expects the libraries were exported to the global space, which is not necessary to be the case. And these days with bundlers it’s likely to be not the case.

«Why is this, and how can I still detect the framework in these cases?» — automatically it’s unlikely you can, at least easily and reliably.

Читайте также:  float

While I could see the usefulness of this goal, I’m very much unsure if there is actually a simple way you could detect the presence of most of these libraries. Javascript libraries can now be «present» in a lot of different ways compared to before. Admittedly, doing this as a browser extension may provide some analysis capabilities a normal page script wouldn’t have.

1 Answer 1

It looks like you have misunderstood how that code detecting libraries work, and of course that relates to understanding the window object.

In a browser javascript environment window is the global object. All variables are defined as properties of the global window object, unless they are defined within a function with the var keyword.

Let’s say you visit a page that uses jQuery library, open the browser console and type jQuery . That should respond with a function, which jQuery is. Essentially jQuery is a variable defined in the global scope, and it is available as a variable by it’s name, and as a property of the window object: window.jQuery .

What libraries do by default if you include them with tag is define themselves as a global variable. So with Backbone.js you will have Backbone global variable defined for you, and it will be available as window.Backbone , because window is the global object.

Similarly, Angular will define angular global variable, Zepto will define Zepto , and so on.

For this reason you should be able to detect any library by the global variables it defines.

A caveat however, is that in modern javascript applications, libraries do not necessarily register a global variable. They may be defined within a scope (a function) of that application. For this reason checking window.Libraryname doesn’t guarantee the page isn’t using this library. And in fact it may be a very difficult task to detect a library in this case.

  1. There are too many frameworks/libraries, so it is up on you to create the list, or find anyone who maintains one. Then you would look into what global variables that framework defines, so you could look for them as the identifier of that framework.
  2. As I explained above, angular is the global variable, also available as window.angular . If you create a scoped angular variable, like function () < var angular = "my angular"; >, you will still be able to get the global one with window.angular .
  3. It is possible that the maintainers of that code became aware of two or more libraries that define Backbone global variable. And only the Backbone we know about, includes the sync function. That might be the reason they additionally check that Backbone.sync is a function. They can’t just check for the Backbone.sync function without checking for Backbone first, because on non-backbone pages that would cause error.
    Similarly, with Underscore, there might be many libraries that define global _ variable, so we can know for sure it is the Underscore library by checking one of it’s methods in work.
  4. As I mentioned above, libraries will not necessarily define a global variable, in which case you will not be able to detect them automatically. As an example, in a modern javascript application, you could use a library as a dependency with Browserify, or RequireJS, in which case the library most likely will not register any global variables.

Источник

Оцените статью