Get client hostname [duplicate] - javascript

How can I read the client's machine/computer name from the browser?
Is it possible using JavaScript and/or ASP.NET?

You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:
function GetComputerName() {
try {
var network = new ActiveXObject('WScript.Network');
// Show a pop up if it works
alert(network.computerName);
}
catch (e) { }
}
It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.
Here is a link to some more info on WScript: More Information

Browser, Operating System, Screen Colors, Screen Resolution, Flash version, and Java Support should all be detectable from JavaScript (and maybe a few more). However, computer name is not possible.
EDIT: Not possible across all browser at least.

Well you could get the ip address using asp.net, then do a reverse DNS lookup on the ip to get the hostname.
From the ASP.NET Developer's cookbook ... Performing a Reverse-DNS Lookup.

It is not possible to get the users computer name with Javascript. You can get all details about the browser and network. But not more than that.
Like some one answered in one of the previous question today.
I already did a favor of visiting your website, May be I will return or refer other friends.. I also told you where I am and what OS, Browser and screen resolution I use Why do you want to know the color of my underwear? ;-)
You cannot do it using asp.net as well.

Try getting the client computer name in Mozilla Firefox by using the code given below.
netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["#mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
Also, the same piece of code can be put as an extension, and it can called from your web page.
Please find the sample code below.
Extension code:
var myExtension = {
myListener: function(evt) {
//netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["#mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
content.document.getElementById("compname").value = compName ;
}
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); //this event will raised from the webpage
Webpage Code:
<html>
<body onload = "load()">
<script>
function showcomp()
{
alert("your computer name is " + document.getElementById("compname").value);
}
function load()
{
//var element = document.createElement("MyExtensionDataElement");
//element.setAttribute("attribute1", "foobar");
//element.setAttribute("attribute2", "hello world");
//document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
//element.dispatchEvent(evt);
document.getElementById("compname").dispatchEvent(evt); //this raises the MyExtensionEvent event , which assigns the client computer name to the hidden variable.
}
</script>
<form name="login_form" id="login_form">
<input type = "text" name = "txtname" id = "txtnamee" tabindex = "1"/>
<input type="hidden" name="compname" value="" id = "compname" />
<input type = "button" onclick = "showcomp()" tabindex = "2"/>
</form>
</body>
</html>

There is no way to do so, as JavaScript does not have an access to computer name, file system and other local info. Security is the main purpose.

No this data is not exposed. The only data that is available is what is exposed through the HTTP request which might include their OS and other such information. But certainly not machine name.

<html>
<body onload = "load()">
<script>
function load(){
try {
var ax = new ActiveXObject("WScript.Network");
alert('User: ' + ax.UserName );
alert('Computer: ' + ax.ComputerName);
}
catch (e) {
document.write('Permission to access computer name is denied' + '<br />');
}
}
</script>
</body>
</html>

There is some infos to parse into the webRTC header.
var p = new window.RTCPeerConnection();
p.createDataChannel(null);
p.createOffer().then((d) => p.setLocalDescription(d))
p.onicecandidate = (e) => console.log(p.localDescription)

An updated version from Kelsey :
$(function GetInfo() {
var network = new ActiveXObject('WScript.Network');
alert('User ID : ' + network.UserName + '\nComputer Name : ' + network.ComputerName + '\nDomain Name : ' + network.UserDomain);
document.getElementById('<%= currUserID.ClientID %>').value = network.UserName;
document.getElementById('<%= currMachineName.ClientID %>').value = network.ComputerName;
document.getElementById('<%= currMachineDOmain.ClientID %>').value = network.UserDomain;
});
To store the value, add these control :
<asp:HiddenField ID="currUserID" runat="server" /> <asp:HiddenField ID="currMachineName" runat="server" /> <asp:HiddenField ID="currMachineDOmain" runat="server" />
Where you also can calling it from behind like this :
Page.ClientScript.RegisterStartupScript(this.GetType(), "MachineInfo", "GetInfo();", true);

Erm is there any reason why you can't just use the HttpRequest? This would be on the server side but you could pass it to the javascript if you needed to?
Page.Request.UserHostName
HttpRequest.UserHostName
The one problem with this is it would only really work in an Intranet environment otherwise it would just end up picking up the users Router or Proxy address...

Related

Use of localStorage and IndexedDB in New Google Sites <Embed HTML> doesn't work

I'm trying to make use of the New Google Sites for a web page that I've developed, however, I'm having trouble storing local data. Local files work fine in windows and apple safari/chrome. Try it from Google Sites, and no joy! Additionally, in safari, an error is thrown, "IDBFactory.open() called in an invalid security context".
I really would like to host my site via google sites without linking to another server. I specifically need locally persistent data for just a few small items. I can't seem to make cookies work either.
Any suggestions?
I have tried this on a Windows 10 Surface Pro 2017, Apple iPad running 12.2 of Safari, Apple Mac Mini running macOs Mojave 10.14. I use SimpleHTTPServer from Windows 10 command line to share the files as a web server. I also email the files and open directly on the specified systems. Finally, I have created a New Google Sites website at https://sites.google.com/view/gerrymap It's very simple, just an Embed HTML element with the below text copied into the source code edit box. All are welcome to hit that page if they desire. Otherwise, use the short posted file below.
Instructions are in the HTML page itself.
All code works fine from a local instance of the html file. Can enter new values for the lat, long, rad, and key, save them, and read them. I can also refresh the page, then read them without storing first, and there is no problem. This proves that the values aren't just session persistent.
From Google Sites is a different matter. I set up a site that uses the html file in this question. When I enter new values and press the save button, IndexedDB fails, but localStorage succeeds in returning the values saved. If I press the refresh button, however, and then read the values without attempting to store first, IndexedDB again fails, but localStorage also fails in that it doesn't retrieve any values.
I believe I've correctly implemented the code (although some out there may take exception, I'm sure. No pride here, critics are welcome).
I've done a bunch of google searches, particularly about google sites and indexeddb/localstorage, and also posted on the google community help forum. Still no success.
Currently, I have no fallback methods, but need something relatively simple. Can anyone throw a little joy my way? Thanks in advance!
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Test Local Storage</title>
<style>
</style>
</head>
<body onload="initializeValues()">
Instructions: <br />
1. Save this sample code in an html file locally and open in a browser.<br />
2. Enter different values into the lat, long, rad, and key edit boxes.<br />
3. Press TrySave to store the values in indexedDB and localStorage.<br />
4. Refresh the webpage from the browser address line<br />
5. Press the individual Try IndexedDB and Try LocalStorage buttons to attempt<br />
6. Try inserting this code into a New Google Site, or access https://sites.google.com/view/gerrymap/home <br />
<br>
<input id="latitude" /> Latitude<br><br>
<input id="longitude" /> Longitude<br><br>
<input id="radius" /> Radius<br><br>
<input id="key" /> Key<br><br>
<button onclick="TryIndexedDB()" title="This tries to load via IndexedDB">Try IndexedDB</button><br><br>
<button onclick="TryLocalStorage()" title="This tries to load via localStorage">Try localStorage</button><br><br>
<button onclick="trySave()" title="This tries to save the data in both methods (IndexedDB, localStorage)">Try Save</button><br><br>
<button onclick="clearAll()" title="Clear the log space at the bottom of this example page">Clear Log</button><br><br>
<div id="hello">
</div>
<script>
"use strict";
function clearAll() {
document.getElementById("hello").innerHTML = "";
}
// tagBeginDefaultsReplace
var navLatitude = 39;
var navLongitude = -76.7;
var navMaxDist = 200;
var navKey = "PleaseAddYourKey";
function initializeValues() {
document.getElementById("latitude").value = navLatitude;
document.getElementById("longitude").value = navLongitude;
document.getElementById("radius").value = navMaxDist;
document.getElementById("key").value = navKey;
}
function trySave() {
navLatitude = document.getElementById("latitude").value;
navLongitude = document.getElementById("longitude").value;
navMaxDist = document.getElementById("radius").value;
navKey = document.getElementById("key").value;
// Save using indexeddb
getLocationDB(true, FinishIndexedDB);
// Save using localStorage
localStorage.setItem('latitude', navLatitude.toString());
localStorage.setItem('longitude', navLongitude.toString());
localStorage.setItem('radius', navMaxDist.toString());
localStorage.setItem('key', navKey.toString());
mylog("Done saving localStorage");
}
function getLocationDB(bSave, callbackf) {
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
var openDB;
try {
var myitem;
openDB = indexedDB.open("SampleDatabase", 1);
openDB.onupgradeneeded = function () {
var db = openDB.result;
var store = db.createObjectStore("SampleStore", { keyPath: "id" });
var index = store.createIndex("PosIndex", ["pos.latitude", "pos.longitude", "pos.radius", "pos.navkey"]);
};
openDB.onsuccess = function () {
// Start a new transaction var db = openDB.result;
callbackf("Successfully opened openDB");
var db = openDB.result;
var tx = db.transaction("SampleStore", "readwrite");
var store = tx.objectStore("SampleStore");
if (bSave) {
if (navLatitude != undefined && navLongitude != undefined && navMaxDist != undefined)
store.put({ id: 0, pos: { latitude: navLatitude, longitude: navLongitude, radius: navMaxDist, navkey: navKey } });
else
store.put({ id: 0, pos: { latitude: "38", longitude: "-75.7", radius: "100", navkey: "Please Enter Mapbox Key" } });
callbackf("Save indexeddb finished");
}
else {
var getNavLoc = store.get(0);
getNavLoc.onsuccess = function () {
if (getNavLoc != undefined
&& getNavLoc.result != undefined) {
callbackf("Succeeded reading from store. Result=" + JSON.stringify(getNavLoc.result));
navLatitude = parseFloat(getNavLoc.result.pos.latitude);
navLongitude = parseFloat(getNavLoc.result.pos.longitude);
navMaxDist = parseFloat(getNavLoc.result.pos.radius);
navKey = getNavLoc.result.pos.navkey;
}
else {
callbackf("Succeeded reading from store. Result=undefined");
navLatitude = navLongitude = navMaxDist = navKey = "undef";
}
initializeValues();
}
getNavLoc.onerror = function () {
callbackf("An error occurred getting indexeddb");
}
}
}
openDB.onerror = function () {
callbackf("An error occurred opening openDB");
}
}
catch (e) {
callbackf("Caught error in try block of indexeddb: " + e.Message);
}
}
function TryIndexedDB() {
getLocationDB(false, FinishIndexedDB);
}
function TryLocalStorage() {
mylog("localStorage read");
navLatitude = localStorage.getItem('latitude');
mylog("latitude=" + navLatitude);
navLongitude = localStorage.getItem('longitude');
mylog("longitude=" + navLongitude);
navMaxDist = localStorage.getItem('radius');
mylog("radius=" + navMaxDist);
navKey = localStorage.getItem('key');
mylog("key=" + navKey);
if (navLatitude == undefined)
navLatitude = "undef";
if (navLongitude == undefined)
navLongitude = "undef";
if (navMaxDist == undefined)
navMaxDist = "undef";
if (navKey == undefined)
navKey = "undef";
initializeValues();
}
function FinishIndexedDB(nSucceeded) {
mylog(nSucceeded);
}
function mylog(logstr) {
document.getElementById("hello").innerHTML += "<br>" + logstr.toString();
}
</script>
</body>
</html >
The problem is the way Google Sites is serving the iframe content. I'm not sure of the exact details behind the scenes, but it seems to have a randomly generated domain every time the page loads. Since localStorage and IndexedDB are associated with a specific domain, this causes the saved data to be "lost" when the page reloads.
As an example, here is the iframe's data from when I first loaded the page:
And here is the iframe's data after refreshing the page:
As you can see, the domain is completely different after refreshing, which means it has a brand new empty database.

How to Change Background Image Based on User Input | HTML, CSS, JS

I have done a lot of research on how to do this, yet I can't seem to find a specific answer. I am trying to allow the user to input a file from their computer, and turn that file into the background of the webpage. My following code is shown below:
<head>
<script>
function changeBackground() {
var input = document.getElementById("background").value;
localStorage.setItem("Background", input);
var result = localStorage.getItem("Background");
$('body').css({ 'background-image': "url(" + result + ")" });
}
</script>
</head>
<body>
<input id="background" type="file" onchange="changeBackground()">
</body>
If someone could please explain to me what I need to do to get this to work, I would very much appreciate it. I already understand I need to use localStorage to make sure that the selected background is remembered, I am just having trouble getting the background to change. If there is already an article on how to do this, I would appreciate a link to it. Thanks!
EDIT
Nikhil and user6003859 explained to me why it isn't working. I guess I just need to figure out how to use Ajax and PHP to change it. If anyone has more advice on this, I would love to hear it. Thanks everyone for helping me solve this problem.
Modern browsers normally restrict access to the user's local files (in this case an image). What you're trying to do is display an image from the user's local filestorage, via the path you get from the <input type='file' /> value.
What you should instead be doing, is uploading the image to your server (probably with ajax, so it feels seamless), and then displaying the file from your server on to your page.
EDIT: Even though this is kind of a new question, I'll give you an example on how to change an element's background based on a URL provided by the user:
var inp = document.getElementById('inp');
var res = document.getElementById('res');
inp.oninput = function()
{
res.style.backgroundImage = 'url(' + inp.value + ')';
};
div
{
width: 5em;
height: 5em;
}
<input type='text' id='inp' />
<div id='res'>
</div>
It's better practice to use file reader.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#file").change(function(){
var length=this.files.length;
if(!length){
return false;
}
changeBackground(this);
});
});
// Creating the function
function changeBackground(img){
var file = img.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){
alert("Invalid File Extension");
}else{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(img.files[0]);
}
function imageIsLoaded(e) {
$('body').css({ 'background-image': "url(" + e.target.result + ")" });
}
}
</script>
</head>
<body>
<input type="file" name="" id="file" value="Click">
</body>
</html>
You cannot do that purely with client-side because of security reasons.
The moment you upload say an image, the browser gives it a "fakepath" like so:
C:\fakepath\<filename>.png
This is a security implementation of the browser - the browser is protecting you from accessing your disk structure.
Hence when you check the value of your input after uploading, you would get the above fakepath ie. C:\fakepath\<filename>.png. Using this as the background obviously would not work.
Usually to achieve this you need to first store it in a server, then fetch the value from the server and apply the background.
To use a local file, store it in a blob
<head>
<script>
function changeBackground() {
var backgroundFile = document.getElementById("background").files[0];
$('body').css({ 'background-image': "url(" + URL.createObjectURL(backgroundFile) + ")" });
}
</script>
</head>
<body>
<input id="background" type="file" onchange="changeBackground()">
</body>

tokbox-opentok passed to one side only

I am using tokbox trial for video chatting on my website. But the problem i am facing is that ::: User 1 can see and hear User 2 clearly. User 2 can see User 1 clearly, but user 2 couldnt here user 1. And code i am using
<html>
<head>
<title>Monkvyasa | Test</title>
<script src='http://static.opentok.com/webrtc/v2.2/js/opentok.min.js'></script>
<script type="text/javascript">
// Initialize API key, session, and token...
// Think of a session as a room, and a token as the key to get in to the room
// Sessions and tokens are generated on your server and passed down to the client
var apiKey = "xxxxxxx";
var API_KEY=apiKey;
var sessionId = "2_MX40NTAyMDgxMn5-xxxxxxxxxxxxxxxxxxxxHBXZEZoWHN-fg";
var token = "T1==cGFydG5lcl9pZD00NTAyMDgxMiZzaWc9ZDNiYjYyZGE2NTBkYmUzMTUyNGNjNDZjYzAzY2NjZWRhZGY3NTEyZjpyb2xlPW1vZGVyYXRvciZzZXNzaW9uX2lkPTJfTVg0xxxxxxxxxxxxxxxxxxxxxxxxBNM1JsYlRCUFdXWkhSSEJYWkVab1dITi1mZyZjcmVhdGVfdGltZT0xNDEzMjAwMjIxJm5vbmNlPTAuMTk1MzEwNTU0MzY1MjEwNSZleHBpcmVfdGltZT0xNDEzMjg0MzY5";
// Initialize session, set up event listeners, and connect
var session;
var connectionCount = 0;
function connect() {
session = TB.initSession(sessionId);
session.addEventListener("sessionConnected", sessionConnectHandler);
session.addEventListener('streamCreated', function(event){
e=event;
console.log(e);
for (var i = 0; i < event.streams.length; i++) {
streams = event.streams;
// Make sure we don't subscribe to ourself
alert("new user connected :)");
if (streams[i].connection.connectionId == session.connection.connectionId) {
return;
}
// Create the div to put the subscriber element in to
var div = document.createElement('div');
div.setAttribute('id', 'stream' + streams[i].streamId);
document.body.appendChild(div);
session.subscribe(streams[i], div.id);
}
});
session.connect(API_KEY, token);
}
function sessionConnectHandler(event) {
var div = document.createElement('div');
div.setAttribute('id', 'publisher');
var publisherContainer = document.getElementById('publisherContainer');
// This example assumes that a publisherContainer div exists
publisherContainer.appendChild(div);
var publisherProperties = {width: 500, height:450};
publisher = TB.initPublisher(API_KEY, 'publisher', publisherProperties);
session.publish(publisher);
}
function disconnect() {
session.disconnect();
}
connect();
</script>
</head>
<body>
<h1>Monkvysa videofeed test!</h1>
<input style="display:block" type="button" id="disconnectBtn" value="Disconnect" onClick="disconnect()">
<table>
<tr>
<td> <div id="publisherContainer"></div></td> <td><div id="myPublisherDiv"></div></td>
</tr>
</table>
</body>
</html>
Thanks in advance
The code looks mostly correct, except you're using an older form of the 'streamCreated' event handler. In the latest version of the API, you no longer need to iterate through the event.streams array, you actually get one invocation of the event handler per stream.
In order to further dig into the problem, would you be able to add a link to a gist containing all the console logs? To make sure the logs are being outputted, you can call OT.setLogLevel(OT.DEBUG); at the beginning of the script.
Lastly, the newer API is greatly simplified and you could save yourself the effort of DOM element creation and iteration. What you have implemented is basically identical to our Hello World sample applications, which you can find in any of our server SDKs, for example here: https://github.com/opentok/opentok-node/blob/61fb4db35334cd30248362e9b10c0bbf5476c802/sample/HelloWorld/public/js/helloworld.js

why call flash function from javascript work but FileReference don't work in flash?

I need call flash function from javascript. I use flash.external and addCallback to do this. all things work well but when I use FileReference in my flash, function did not open my browser ...
please see below describtion:
I call my function in javascript with this code:
<input type="button" value="Browse" onclick="sendToFlash('Hello World! from HTML');" />
you can see all my HTML as below:
<html>
<head>
<title>Upload test</title>
</head>
<script>
function hello (size) {
alert ("size hast: " + size);
}
function sendToFlash(val){
var flash = getFlashObject();
flash.new_browser(val);
}
var flash_ID = "Movie2";
var flash_Obj = null;
function getFlashObject(){
if (flash_Obj == null){
var flashObj;
if (navigator.appName.indexOf( "Microsoft" ) != -1){
flashObj = window[flash_ID];
}
else{
flashObj = window.document[flash_ID];
}
flash_Obj = flashObj;
}
return flash_Obj;
}
</script>
<body>
<center>
<embed width="560" height="410" type="application/x-shockwave-flash"
flashvars="sampleVars=loading vars from HTML"
salign="" allowscriptaccess="sameDomain" allowfullscreen="false" menu="true" name="Movie2"
bgcolor="#ffffff" devicefont="false" wmode="window" scale="showall" loop="true" play="true"
pluginspage="http://www.adobe.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"
quality="high" src="Movie2.swf">
</center>
<input type="button" value="Browse" onclick="sendToFlash('Hello World! from HTML');" />
</body>
</html>
when I click Browse in html page, javascript call sendToFlash function and SendToFlash function send my string (Hello World! from HTML) to flash.
in flash I get this string with below code:
resultsTxtField.text = "";
uploadButton.onPress = function () {
return browse_file("Hello World! from Flash");
}
import flash.external.*;
ExternalInterface.addCallback("new_browser", this, browse_file);
function browse_file (my_test_val) {
_root.resultsTxtField.text = "val: " + my_test_val;
import flash.net.FileReference;
var fileTypes:Array = new Array();
var imageTypes:Object = new Object();
imageTypes.description = "Images (*.jpg, *.jpeg, *.gif, *.png)";
imageTypes.extension = "*.jpg; *.jpeg; *.gif; *.png";
fileTypes.push(imageTypes);
var fileListener:Object = new Object();
var btnListener:Object = new Object();
var fileRef:FileReference = new FileReference();
fileRef.addListener(fileListener);
fileRef.browse(fileTypes);
fileListener.onCancel = function(file:FileReference):Void
{
_root.resultsTxtField.text += "File Upload Cancelled\n";
}
fileListener.onSelect = function(file:FileReference):Void
{
_root.resultsTxtField.text += "File Selected: " + file.name + " file size: "+ file.size + " file type: " + file.type;
getURL("javascript:hello("+file.size+");");
}
}
I have only one Scene and this code is on root of this Scene. and I have one movie clip named uploadButton and has only a rectangle that work as button in this sample.
when you click on rectangle browse_file("Hello World! from Flash"); called and a browser open that you can select a photo to upload.
when you click on browse in html same process must do but as you see variable send to function but browser to select a photo did not open any more.
I try several ways. for example I set new function to open only picture browser or set new Scene or use gotoAndPlay and more but there is another problem.
you can download my source from below link:
http://www.4shared.com/zip/YTB8uJKE/flash_uploader.html
note that javascript onclick="sendToFlash('Hello World! from HTML');" don't work in direct opening. you must open it in localhost.
I'll be so so happy for any clue.
thanks so much
Reza Amya
You can't programmatically call browse(), it has to be from a mouse click inside Flash: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html#browse()
In Flash Player 10 and Flash Player 9 Update 5, you can only call
this method successfully in response to a user event (for example, in
an event handler for a mouse click or keypress event). Otherwise,
calling this method results in Flash Player throwing an Error
exception.
after a day reading I know that it is impossible for security reasons.
then you can't open file reference with addCallback javascript code any way. for more information read fileReference browse from js, simulate keypress in flash workaround
Thanks again
Reza Amya

Send Variable from one html to another

I have 2 HTML pages, send.html and receive.html
In each page I have a textield. The thing that I'm trying to do is whenever the "value" of the textfield in the send.html changes, automatically parse the data to the textfield value of the receive.html. When I say automatically I mean without the need of a button or reloading the pages.
To sum up.. I have this textfiled in the send.html
<input type="text" id="send" size="25" value="Val1">
And this text field in the receive.html
<input type="text" id="receive" size="25" value="Val2">
I want to "monitor" somehow the Val1, and if it changes I want Val2=Val1
For my purpose I cant use jquery.
Is that possible?
I think you are missing a big picture. Data sending and receiving needs some server side interaction like using PHP, ASP, JSP, Python etc., unless you are ok with cookies.
When you update a field in one age, that data needs to go the server somehow for another page to catch. Either way, the way you want it to go automatic is not possible right now. However, I will provide a solution of how you can do this using jQuery and PHP. But if you want?
Update
So, it seems cookies is the only option. Follow the following steps
Create a new file cookie.js and place the following code inside
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
Next, create two html file "test1.html" and "test2.html" with this markup
<html>
<head>
<script src="cookie.js"></script>
</head>
<body>
<input type="text" id="text1" name="text1" />
</body>
</html>
Now, on test1.html add the following script on the head
<script>
window.onload = function() {
document.getElementById("text1").onchange = function() {
// ^ use onkeyup if you want this to occur as you type
setCookie("shared", this.value, 1);
alert('oK, val changed so lets check it');
};
};
</script>
On Test2.html add the following Script on the head
<script>
var checkandupdate = function() {
var shared = getCookie("shared");
if(shared) {
document.getElementById("text1").value = shared;
}
};
window.onload = function() {
int = setInterval("checkandupdate()",1000);
};
</script>
Now
Open both pages
Go to test1.html and type something then press tab to get the alert message.
Open the test2.html, it should be update within 1 second
After the demo works, Update the field names as you need
Enjoy ;)
In your second HTML page , let's say we call it like page-2.html?send=xyz when the value is being changed , you add the following JS Code :
function getQueryString() {
var result = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
var sendValue= getQueryString()["send"];
document.getElementById("receive").value=sendValue;
if you want to use without cookie for improving the performance.. you can use this library it uses window.name to carry the values.. however it will not work if the user opens in new tab.. still it is good.. only thing is you should handle new tab situation..
Hope this helps.. especially it will help if it is a html based front end..

Categories

Resources