Get current username on the client side on SharePoint 2007 - javascript

I need to create a simple static web part - the only dynamic part is the current user login name (needs to be included in a URL parameter in a link).
I'd rather just use a content editor web part instead of a custom web part that I'll need to deploy. In fact, I already did that using JavaScript and ActiveX (WScript.Shell - full code below)
Is there a better, more native way to do it? What I don't like about the ActiveX approach is that it requires more liberal configuration of IE, and even when I enable everything ActiveX-related in the security settings there is still a prompt that needs to be clicked.
Cross-browser support is not a major issue, it's intranet - but will be a nice extra, too.
One way I can think of is to scrape the username from the top-right hand corner with jQuery (or just JavaScript), but is there something even cleaner?
Or maybe someone has already done the scraping and can share the code to save me some time ;-)
Here's my current solution:
<script language="javascript">
function GetUserName()
{
var wshell = new ActiveXObject("WScript.Shell");
var username = wshell.ExpandEnvironmentStrings("%USERNAME%");
var link = document.getElementById('linkId');
link.href = link.href + username.toUpperCase();
}
</script>
<P align=center>
<a id="linkId" onclick="GetUserName();" href="<my_target_URL>?UserID=">open username-based URL</a>
</P>

Include this Web part token in your content editor web part:
_LogonUser_
It outputs the same value as Request.ServerVariables("LOGON_USER")
I've done this before including in a hidden span and plain old document.getElementById to get the innertext.

My conclusion is that there's no better way to do that (which is also sufficiently easy).
I checked the source of the page and the username is not anywhere there, so can't be scraped by JavaScript/jQuery. The browser doesn't seem to be sending it with the request (as it does with your local IP and other client-related information), so can't be obtained from headers either.
The only other approach I can conceive is calling a web service from the client-side that would be an overkill for my scenario.

Related

How can I let someone know that the click on the link comes from my site

Hello fellow programmers. My case is - I have many links on my website, each of them directs to a different website. How can I let that website which stored its link on my website know, that the user's click comes from my website?
I've read something about utm_source=MySite. Is it the thing I'm looking for?
And if so - where should I drop it? At the end of the link?
<a href={example.com/something/utm_source=MySite}>Link</a>?
Thank you for any kind of help.
utm_source is a URL query string parameter that was originally part of a referrer tracking strategy invented by a company called Urchin Traffic Monitor. They were since bought by Google and the technology sort of lives on now as part of Google Analytics.
This way of tracking is not part of any Web or other standard though, mind you.
There is some information available at Google's.
Since utm_source is a query string variable, if you wish to use this patent-pending (that's right) strategy, these go after the pathname in the URL in your links to third parties, like:
Visit Example.com!
That's all there is to it, really. There are other variables like you yourself mentioned that go with the utm_source variable.
I think also you should research other alternative solutions that may suit you better.
As a bonus, there is no need to patch all your document links manually to include the query string variable(s), just run the following statement when your document is at least interactive (document.readyState is not "LOADING", so the links are actually loaded):
for(const link of document.links) link.href = (function(URL) { URL.searchParams.set("utm_source", "mydomain.com"); return URL; })(new URL(link.href));
You should probably check to not include links that have no hostname or use your own domain explicitly -- no need to include referrer then, is it.

Need to point my javascript or other script source to another website

Ultimatly what I want to do is look for, is the text It's just you! or It's not just you! within the container ID of: '< div id="container">' within the source of the resulting page of isup.me/echelonservices.co.uk.
I have found a way to do this now, but cannot point the Java to the correct site. What I have done is use the following URL: isup.me/echelonservices.co.uk. However, I am having problems doing this. Can someone let me know of a way of either using Javascript or another script source that can be used, without hosting the webpage from webserver. So running the webpage from local client computer.
Here is my last attempt I have come up with and failed miserably so far:
<script type="text/javascript">
//Specify where the sctipt should be running the code against.
window.location.protocol = "http"
window.location.host = "isup.me/echelonservices.co.uk"
//Look for the Class ID and output to a variable.
element = document.getElementById('container');
var Status = element.textContent || element.innerText;
//If the "Status" says: UP write UP, DOWN write DOWN and anything else write Status could not be determined!
if (Status=="UP") {document.write('<div style="color:#00BB00;font-family:Arial;font-weight:bold">UP</div>')}
else {if (Status=="DOWN") {document.write('<div style="color:#FF0000;font-family:Arial;font-weight:bold">DOWN</div>')}
else {document.write('<div style="color:#EDA200;font-family:Arial;font-weight:bold">WARNING:<br>Status could not be determined!</div>')};};
</script>
Fortunately, what you're doing isn't possible. JavaScript cannot read data from another domain (unless that domain is set up explicitly to allow it) - even if that domain is localhost. Otherwise, it would be possible to create a web page that loads Facebook in a hidden IFrame and steals a bunch of confidential user data.
What you'll need to do instead is implement this same logic up on your own web server, using the server side programming language of your choice (PHP, Java, C#, etc). You'd initiate an HTTP request to the desired server, parse the results accordingly, and then echo the results to the client. Basically, you're creating a proxy to that service.
If you're trying to do this without using a web server at all, you might want to check into another client-side technology such as WPF, Air, WinForms, Java, etc.
If you are using firefox, element.innerText isn't supported. Use element.innerHTML instead. Also, I'm not sure if this is a typo, but you have an extra closing bracket around your final else statement. I would recommend using a different syntax for your if statements to make them neater:
if (Status=="UP") {
document.write('<div style="color:#00BB00;font-family:Arial;font-weight:bold">UP</div>')
}
else if (Status=="DOWN"){
document.write('<div style="color:#FF0000;font-family:Arial;font-weight:bold">DOWN</div>')
}
else {
document.write('<div style="color:#EDA200;font-family:Arial;font-weight:bold">WARNING <br>Status could not be determined!</div>')
}

Encryption of the link address <a href="http://www.mycompany.com> so it does not appear in source view on IE toolbar

This is probably a simple question but I can't seem to find what I am looking for on the web so here it goes. I have a link on my company INTRAnet site that senior management does not want the employees to see the actual web address (via the source option on the View tab of IE).
Please let me know how I can do this in HTML, asp.net or JS.
Thanks!
:)
You can't. Tell senior management to quit being so secretive.
Not sure if this is what you want, but here is a similar Question:
php encrypt and decrypt
Does it help at all? There is another, but it is a php code:
http://php.net/manual/en/function.mcrypt-encrypt.php
Also, what language are you looking to implement the code?
Alernatively, you can use this site: http://www.iwebtool.com/html_encrypter and on the box you type your html e.g.
This is your post link
Then use the "Encrypt" button. It will return you the javascript you are looking for.
E.g.
"<"Script Language='Javascript'>
document.write(unescape('%3C%61%20%68%72%65%66%
3D%22%68%74%74%70%3A%2F%2F%73%74%61%63%6B%6F%76%65%72%66%6C%
6F%77%2E%63%6F%6D%2F%70%6F%73%74%73%2F%31%35%39%33%34%36%39%
36%22%3E%54%68%69%73%20%69%73%20%79%
6F%75%72%20%70%6F%73%74%3C%2F%61%3E'));
</Script>
No jsFiddle because that javascript isn't allowed.
First and foremost, it's impossible to hide the url from the browser. The browser has to request the webpage from the server, and even if the url was obscured somehow, it would have to be plaintext in the HTTP Request, which would open it up to a man-in-the-middle utility like Fiddler.
Second, this feels like security through obscurity. Resources that certain people shouldn't have access to should be locked down explicitly, not just hidden because the user doesn't know the url (yet).
However, purely as a thinking exercise... I suppose... you could write a handler that knows the real url, uses code to retrieve the content of the page, and then writes that to the response. So the users would see the handler url, but not where the handler is pulling it's data from. However, you'd then have to go to great lengths to find all links and resources on the page and convert those references to also go through your handler.
Of course, practically speaking, I think this concept is silly. There's some problem your senior management is trying to solve, and hiding the url from the user is not the answer.
If upper management is this secretive then it's a safe bet that you also already have IT people who have browsers locked down as well, meaning Internet Explorer. It's possible that your IT team might be able to force the address bar to hide for all browsers within your company. I don't think that this can be done on a per request basis. Meaning that the address bar would either be on or off all the time.
According to this post your IT team might be able to update the registry to hide the address bar like so:
Run following RegKey:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Internet Explorer\ToolBars]
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Internet Explorer\ToolBars\Restrictions]
"NoNavBar"=dword:00000001
Here's a google search that might also offer additional information.
Well rather than making it disappear you can make it hard for others to see through and even impossible for those who have no knowledge of base-64. Here is a code :
var a = document.querySelectorAll("*"), b = 0;
for ( b = 0; b < a.length; b ++ ) {
if ( a[b].hasAttribute("data-href") ) {
a[b].href = atob( a[b].getAttribute("data-href") );
};
};
Now you can call something like this :
<a data-href="aHR0cDovL3d3dy5teWNvbXBhbnkuY29t">Go</a>
By using btoa() I converted "http://www.mycompany.com" to "aHR0cDovL3d3dy5teWNvbXBhbnkuY29t" in base-64 and designed "data-href" to understand the encoding. Behind all this it will look and act like :
Go

How to manipulate Javascript websites in Perl

I have been asked to automate the logging into a webapp(what I assume to be one, that runs a lot of .aspx and .js scripts) that, currently, can only run in IE. Now i am programming in Perl and have tried to use Win32::IE::Mechanize to run the IE browser and log in. What i did was try an extract all the forms from the webapp, and given the users information, fill out the required forms, but this is where the problem arises, when I try and run the subroutine no forms appear......
So then I transitioned into WWW::Mechanize and used the post subroutine(from LWP::UserAgent) which solved the problem for the most part. Now i've run into a problem in the response, from the server, I get this script as the content of the response and I don't know what to do with it.
So my question is: Using Perl how can I go about to manipulate a Javascript functions in a website? Would that even be a valid solution to the problem?
I am open to writing this in other programming languages as well. Thanks in advance for the help!
(So that I can fully log in to the webapp)
Update: The content of the response:
var msgTimerID;
var strForceLogOff = "false";
function WindowOnLoad(){
if ("false" == "true" && "false" == "false")
MerlinSystemMsg("",64);
if ("false"=="true")
msgTimerID = window.setInterval("MerlinSystemMsg(10095,64)", 300000,'javascript');
}
function MyShowModal(){
showModalDialog("", window, strFeatures);}
function clearMsgInterval(){
window.clearInterval(msgTimerID);
}
function WindowOnUnLoad(){
if(top.frames(0).document.getElementById("OPMODE").value =="LOGOFF"){
strFeatures = "width=1,height=1,left=1000,top=1000,toolbar=no,scrollbars=no,menubar=no,location=no,directories=no,status=yes,resizable=1";
window.open("ForceLogOff.aspx","forcelogout",strFeatures);
}
}
window.onbeforeunload = WindowOnUnLoad;
window.onload = WindowOnLoad;
There is also this Frame Title that has the src:
FRAME TITLE="Service Desk Express Navigator" SRC="options_nailogo.aspx" MARGINWIDTH=0 MARGINHEIGHT=0 NORESIZE scrolling=no
Trying to emulate the browser with a fully functioning JS engine is going to be a mighty big task. Instead, I'd suggest that you just try to emulate the actual interaction with the web site and not care what HTML/JS is actually sent back. Your server side code doesn't care how the HTTP submissions take place, only that they do. Admittedly this is more fragile if the forms change a lot, but at least you're not trying to implement a full browser.
So look at modules like LWP::UserAgent, HTTP::Request and HTTP::Response.
I'm copying and pasting my answer to your other duplicate question here
(You should consider deleting one of these?)
That content is the website source :)
How WWW::Mechanize deals with FRAME SRC as a link:
Note that <FRAME SRC="..."> tags are parsed out of the the HTML and
treated as links so this method works with them.
You'll want to use follow_link on that link.
As far as dealing with Javascript, there is support for a Firefox Add-on called MozRepl that you can use in conjunction with WWW::Mechanize::Firefox that I have used in the past to call Javascript code while crawling a page.

Take Screenshot of Browser via JavaScript (or something else)

For support reasons I want to be able for a user to take a screenshot of the current browser window as easy as possible and send it over to the server.
Any (crazy) ideas?
That would appear to be a pretty big security hole in JavaScript if you could do this. Imagine a malicious user installing that code on your site with a XSS attack and then screenshotting all of your daily work. Imagine that happening with your online banking...
However, it is possible to do this sort of thing outside of JavaScript. I developed a Swing application that used screen capture code like this which did a great job of sending an email to the helpdesk with an attached screenshot whenever the user encountered a RuntimeException.
I suppose you could experiment with a signed Java applet (shock! horror! noooooo!) that hung around in the corner. If executed with the appropriate security privileges given at installation it might be coerced into executing that kind of screenshot code.
For convenience, here is the code from the site I linked to:
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
...
public void captureScreen(String fileName) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}
...
Please see the answer shared here for a relatively successful implementation of this:
https://stackoverflow.com/a/6678156/291640
Utilizing:
https://github.com/niklasvh/html2canvas
You could try to render the whole page in canvas and save this image back to server. have fun :)
A webpage can't do this (or at least, I would be very surprised if it could, in any browser) but a Firefox extension can. See https://developer.mozilla.org/en/Drawing_Graphics_with_Canvas#Rendering_Web_Content_Into_A_Canvas -- when that page says "Chrome privileges" that means an extension can do it, but a web page can't.
Seems to me that support needs (at least) the answers for two questions:
What does the screen look like? and
Why does it look that way?
A screenshot -- a visual -- is very necessary and answers the first question, but it can't answer the second.
As a first attempt, I'd try to send the entire page up to support. The support tech could display that page in his browser (answers the first question); and could also see the current state of the customer's html (helps to answer the second question).
I'd try to send as much of the page as is available to the client JS by way of AJAX or as the payload of a form. I'd also send info not on the page: anything that affects the state of the page, like cookies or session IDs or whatever.
The cust might have a submit-like button to start the process.
I think that would work. Let's see: it needs some CGI somewhere on the server that catches the incoming user page and makes it available to support, maybe by writing a disk file. Then the support person can load (or have loaded automatically) that same page. All the other info (cookies and so on) can be put into the page that support sees.
PLUS: the client JS that handles the submit-button onclick( ) could also include any useful JS variable values!
Hey, this can work! I'm getting psyched :-)
HTH
-- pete
I've seen people either do this with two approaches:
setup a separate server for screenshotting and run a bunch of firefox instances on there, check out these two gem if you're doing it in ruby: selenium-webdriver and headless
use a hosted solution like http://url2png.com (way easier)
You can also do this with the Fireshot plugin. I use the following code (that I extracted from the API code so I don't need to include the API JS) to make a direct call to the Fireshot object:
var element = document.createElement("FireShotDataElement");
element.setAttribute("Entire", true);
element.setAttribute("Action", 1);
element.setAttribute("Key", "");
element.setAttribute("BASE64Content", "");
element.setAttribute("Data", "C:/Users/jagilber/Downloads/whatev.jpg");
if (typeof(CapturedFrameId) != "undefined")
element.setAttribute("CapturedFrameId", CapturedFrameId);
document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("capturePageEvt", true, false);
element.dispatchEvent(evt);
Note: I don't know if this functionality is only available for the paid version or not.
Perhaps http://html2canvas.hertzen.com/ could be used. Then you can capture the display and then process it.
You might try PhantomJs, a headlesss browsing toolkit.
http://phantomjs.org/
The following Javascript example demonstrates basic screenshot functionality:
var page = require('webpage').create();
page.settings.userAgent = 'UltimateBrowser/100';
page.viewportSize = { width: 1200, height: 1200 };
page.clipRect = { top: 0, left: 0, width: 1200, height: 1200 };
page.open('https://google.com/', function () {
page.render('output.png');
phantom.exit();
});
I understand this post is 5 years old, but for the sake of future visits I'll add my own solution here which I think solves the original post's question without any third-party libraries apart from jQuery.
pageClone = $('html').clone();
// Make sure that CSS and images load correctly when opening this clone
pageClone.find('head').append("<base href='" + location.href + "' />");
// OPTIONAL: Remove potentially interfering scripts so the page is totally static
pageClone.find('script').remove();
htmlString = pageClone.html();
You could remove other parts of the DOM you think are unnecessary, such as the support form if it is in a modal window. Or you could choose not to remove scripts if you prefer to maintain some interaction with dynamic controls.
Send that string to the server, either in a hidden field or by AJAX, and then on the server side just attach the whole lot as an HTML file to the support email.
The benefits of this are that you'll get not just a screenshot but the entire scrollable page in its current form, plus you can even inspect and debug the DOM.
Print Screen? Old school and a couple of keypresses, but it works!
This may not work for you, but on IE you can use the snapsie plugin. It doesn't seem to be in development anymore, but the last release is available from the linked site.
i thing you need a activeX controls. without it i can't imagine. you can force user to install them first after the installation on client side activex controls should work and you can capture.
We are temporarily collecting Ajax states, data in form fields and session information. Then we re-render it at the support desk. Since we test and integrate for all browsers, there are hardly any support cases for display reasons.
Have a look at the red button at the bottom on holidaycheck
Alternatively there is html2canvas of Google. But it is only applicable for never browsers and I've never tried it.
In JavaScript? No. I do work for a security company (sort of NetNanny type stuff) and the only effective way we've found to do screen captures of the user is with a hidden application.

Categories

Resources