I was wondering how I would get the name of the current user in JavaScript as part of an HTML document.
In Java, one would type System.getProperty("user.name"); to achieve this. What is the alternative to this in JavaScript?
JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.
JavaScript will not be able to determine your Windows user name.
There is no fully compatible alternative in JavaScript as it posses an unsafe security issue to allow client-side code to become aware of the logged in user.
That said, the following code would allow you to get the logged in username, but it will only work on Windows, and only within Internet Explorer, as it makes use of ActiveX. Also Internet Explorer will most likely display a popup alerting you to the potential security problems associated with using this code, which won't exactly help usability.
<!doctype html>
<html>
<head>
<title>Windows Username</title>
</head>
<body>
<script type="text/javascript">
var WinNetwork = new ActiveXObject("WScript.Network");
alert(WinNetwork.UserName);
</script>
</body>
</html>
As Surreal Dreams suggested you could use AJAX to call a server-side method that serves back the username, or render the HTML with a hidden input with a value of the logged in user, for e.g.
(ASP.NET MVC 3 syntax)
<input id="username" type="hidden" value="#User.Identity.Name" />
If the script is running on Microsoft Windows in an HTA or similar, you can do this:
var wshshell=new ActiveXObject("wscript.shell");
var username=wshshell.ExpandEnvironmentStrings("%username%");
Otherwise, as others have pointed out, you're out of luck. This is considered to be private information and is not provided by the browser to the javascript engine.
I think is not possible to do that. It would be a huge security risk if a browser access to that kind of personal information
Working for me on IE:
<script type="text/javascript">
var WinNetwork = new ActiveXObject("WScript.Network");
document.write(WinNetwork.UserName);
</script>
...but ActiveX controls needs to be on in security settings.
Related
Looking into using Google Cloud Print, it seems that it is quite complicated regarding OAuth2, the various tokens/client ids etc.
What is the simplest possible way to print a PDF from a web page?
Implemented client side in Javascript with AJAX (so with CORS) or server side with Java (but preferrably not too many jars needed)
PDF document can be sent as binary or referred to as publicly available URL
Preferrably no user login, must be with some kind of "service" authorization
The same application is already using API keys for google maps geocoding. So re-using these keys, if possible, would be the ideal option.
It would be great with some pointers on how to do this in the simplest possible manner possible.
The simplest possible scenario is using the GCP Web Element, as described in: https://developers.google.com/cloud-print/docs/gadget
It boils down to including the print gadget scripts, creating a container to host the button and creating the print gadget in it:
<html>
<head>
</head>
<body>
<div id="print_button_container"></div>
<script src="https://www.google.com/cloudprint/client/cpgadget.js">
</script>
<script>
window.onload = function() {
var gadget = new cloudprint.Gadget();
gadget.setPrintButton(
cloudprint.Gadget.createDefaultPrintButton("print_button_container")); // div id to contain the button
gadget.setPrintDocument("url", "Test Page", "https://www.google.com/landing/cloudprint/testpage.pdf");
}
</script>
</body>
</html>
If you are not logged-in your GCP account you will be shown the appropriate log-in dialog and then you'll select the target printer.
Check the fiddle here:
https://jsfiddle.net/0ncsuqra/
Say I have two html pages and open them in two tabs. I'd like to make them communicate. As example when I click on a button on the first page, then it should call a function that does something on the second page.
function Test() {
document.getElementById('test').innerHTML = "Test";
}
<!DOCTYPE html>
<html>
<head>
<script src="index.js"></script>
</head>
<body>
<button onclick="Test()">Click here</button>
</body>
</html>
And the second page:
<!DOCTYPE html>
<html>
<head>
<script src="index.js"></script>
</head>
<body>
<p id="test"></p>
</body>
</html>
When I click the button on the first page it should write Test in the p tag on the second page. They can use the same JavaScript file. But how can I achieve this?
You can't do this with just JavaScript. The point is: JS is a client-side language which means that it is downloaded by a client (a browser) and is run by it (not by server). For the 2 pages to communicate, you have establish the communication somehow, via some medium. The medium can be:
web itself. 2 clients can communicate directly, but only if they know each others' address. How would they get those? By the help of the server (which brings us to the second option below) or by manual configuration which is very impractical (some more details may be found in context of WebRTC)
your server. Ok, that's the most common approach but that involves more than just JS: this requires a server-side language (PHP, Python, C++, Java, whatever)
your browser. There's a special case where you can establish such a communication: if you open your second page in the same browser from your first page in a special way so that the second one is "under control" of the first one, you can "command" the second one to do some stuff from the first one
So, if you're interested in the third option, you should read about window.open, window.opener, window.parent.
var newWindow = window.open(url, name, params);
will open a new window (say your second page) and bring you a variable newWindow which is a reference to the window object of the opened window. Try for instance
newWindow.write("haha, I'm controlling this stuff!");
Likewise, in the second window you can use
var oldWindow = window.opener;
There's also a number of methods you can use (window``.close, .moveBy, .moveTo, .resizeBy, .resizeTo etc etc).
Remember, however, that this interaction will be limited to your browser: if you change something as it is displayed in your browser (like add some text to a page) this won't affect the actual pages stored on your server because this requires your server do something via some server-side scripts.
PS to advance this technique, you may want to read about window.postMessage but that's mostly designed for communication between pages that are cross-domain.
PPS Actually, there's more!
One thing to note is localStorage and sessionStorage have setItem method which generates 'storage' events on window (try localStorage.setItem('key', 'value'); and window.addEventListener('storage', event => console.log(event.key));).
Another, like Anderson Green has noted, is Broadcast Channel API (try const channel = new BroadcastChannel('my_channel'), channel.postMessage('Hi there!') and channel.addEventListener('message', event => console.log(event))).
There's also SharedWorkers and Service Workers.
Finally, you can use some off-the-shelve solutions like tabs-router, Hermes, Visibility, Duel and SE.
Those who speak Russian may also find more useful details in this article (wow!).
Try using cookies. It's the simplest way I can think of. This website might seem helpful: https://www.w3schools.com/js/js_cookies.asp
I have a html like this that I deliver to the client from my web server
<html>
<head>
<script type="text/javascript">
var myapp = myapp || {};
myapp.settings = {"abc", "xyz", "123"};
</script>
</head>
</html>
In the rest of my client app, I have checks that look at the myapp.settings object.
Is myapp.settings secure? Can a hacker add strings or remove strings from myapp.settings? If so, what are some example ways to do so?
No, it is not secure. In fact, nothing in a web page is completely secure.
In your particular example, here are some examples for how your myapp object can be manipulated:
The end-user can open the browser console and type in a line of code to change that object.
The end-user can open the browser debugger, set a breakpoint and when it hits that breakpoint, edit that object.
The end-user can download or create a bookmarklet that when clicked on would modify the myapp object.
The end-user can set up a proxy that intercepts the incoming page, modifies it and then sends it on to the browser.
An attacker can intercept the page on its way to you and modify it (as it goes through your ISP for example). Note: this would be much less likely if you were using https.
Because nothing in the browser is completely secure, security issues have to be addressed with a specific need in mind and then options are explored to handle those specific concerns.
No, it is not secure.
Yes, a user can manipulate the state of your myapp.settings object rather easily.
As long as someone can execute a script in that app, they can modify myapp.settings. However, you can prevent this by using Object.freeze() function on it:
Object.freeze(myapp.settings);
myapp.settings.test = 42;
console.log(myapp.settings.test); // undefined
I save this file as test.html and when I opened this file in IE, I am getting Information Bar for ActiveX Controls, Is there any way we can disable this thing using javascript code or jQuery code?
<html>
<body>
<h1>My First Web Page</h1>
<script type="text/javascript">
if(navigator.appName == "Microsoft Internet Explorer")
{
window.location = "http://www.google.com/"
}
else
{
window.location = "http://www.yahoo.com/"
}
</script>
</body>
</html>
And I just wanted to make sure, as I am running locally on my box so that is the reason it is showing ActiveX control Information bar? And Once I upload this file to a remote server and access it from there then this active x bar will not appear??
But is there any way programmatically to disable this information bar? Any suggestions will be appreciated.
Use Mark of the Web (MOTW). We can disable the ActiveX controls warning by putting following code before the opening html tag:
<!-- saved from url=(0014)about:internet -->
<html>
<body>
......
</body>
</html>
The above code is call “Mark of the Web (MOTW)”, this is a feature of Windows Internet Explorer that enhances security by enabling Internet Explorer to force Web pages to run in the security zone of the location the page was saved from
The Information Bar you're seeing is unrelated to ActiveX (even though it might say "ActiveX"). It's simply telling you that a IE isn't running scripts on a local file, a security precaution.
Yes, when accessed via HTTP, the warning won't appear.
There's no way to programmatic disable it because (1) your code isn't running in the first place; and (2) doing so would circumvent the security restriction that this is meant to be. Use the MOTW.
If you just want pages to work on your machine, go to Tools, Internet Options, Advanced, and check Allow active content to run in files on My Computer. I'd only enable this option while developing, however.
Some company is providing me with web-based API for using their services. I have no problem calling this API functions from within web brower:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript"
src="http://someaddress.com?&key=somekey"></script>
<script type="text/javascript">
var object = new SomeObject();
object.SomeFunction();
</script>
</head>
I am interested in return value of SomeFunction().
How would I get this return value from windows application?
You can use a tool like Firebug. That will let you watch the actual HTTP requests, and step through the JavaScript. In combination, that will let you see where the return value comes from.
Once you understand this, you can replicate the requests (and possibly parts of the JavaScript logic) in your Windows app using an appropriate HTTP client library.
Note that this may be a violation of the TOS.
You can embed web browser control in WinForm and return value from SomeFunction
into some DOM element, then you can access that element from WinForm.WebBrowser1.
There are also javascript emulators available, I think you can even use JSCRIPT dll from c#
but that may not work if SomeFunction() depends on DOM.