How to override navigator.plugins in javascript or

2020-07-18 23:29发布

问题:

navigator.plugins in javascript provides the plugins-array for the browser. Is it possible to set this array to null? I tried that(navigator.plugins = null;) but it was not setting to null. Also, I tried to set it to an empty array(navigator.plugins = new Array();)

Also if this is possible, is this a good practice?

回答1:

In Chrome, it is possible to do this by setting window.navigator to null. However, I'm not sure why you would do this. Since you're dealing with JavaScript, it would be possible for someone to use a debugger to stop your code from running and intercept this code before you're able to set it to null.

Moreover, the navigator object generally contains information about the client machine, and if I'm the user, I most likely know more about my computer than your server does, so disabling this wouldn't really have any measurable advantage that I can see.

Also, this would have to happen on every pageload.

Finally, I don't know how other browsers would handle this, but you very well may run into trouble trying to do this in other browsers.

In short, I don't think it's a good practice; however, you didn't provide details on why you want to do this. Without that information, I cannot give you a fair answer other than it's not a good idea. So you'll of course need to examine why you want to do this and determine if it's really worth the hassle.



回答2:

There are some web applications which first retrieve browser name. The navigator object of UIWebView does not return enough information. for e.g. navigator.userAgent returns

Mozilla/5.0 (iPad; CPU OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13C75

These web applications failed to detect browser name from above information and throw exceptions unsupported browser.

To handle such situation I override navigator object as given below and yes the web application was able to run perfectly. This is failed in firefox but my requirement was to support UIWebView only

var __originalNavigator = navigator;
navigator = new Object();
navigator.__proto__ = __originalNavigator;
navigator.__defineGetter__('userAgent', function () { return "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36"; });
navigator.__defineGetter__('plugins', function () { return []; });


回答3:

I have never heard of anyone wanting to set the plugins array to null, and quite frankly I don't understand what benefit it would yield if you did so. Like jmort253 said, it is possible to set it to null in chrome, but in other browsers you may not be able to. Keep in mind though that navigator.plugin is not a JavaScript array but a pluginArray