Javascript Websocket closed unexpectedly when script is loaded externally - javascript

While building a chat application in Django, I used embedded javascript and it worked. But, if I write the same code in external javascript then the WebSocket gets closed. I have checked all the links and static file path. The script is loaded completely but the WebSockets gets closed after they open.
Here's the tutorial from Official Django Channels website, and that javascript is working in embedded form only not in an external script.
And, here's my Github repo where I've implemented Websockets.
How can I write JS code in external script instead of embedded? I've Googled but found no help and even this question hasn't been answered yet.
Here's the code I'm talking about and the websockets won't work if defined externally:
<!-- chat/templates/chat/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br/>
<input id="chat-message-input" type="text" size="100"/><br/>
<input id="chat-message-submit" type="button" value="Send"/>
</body>
<script>
var roomName = {{ room_name_json }};
var chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/');
chatSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
var message = data['message'];
document.querySelector('#chat-log').value += (message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
var messageInputDom = document.querySelector('#chat-message-input');
var message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
};
</script>
</html>

Related

Cannot reproduce query param html injection

We have an embedded script running on the page of one our clients. We received a report from them that the query params we send to that page are not properly guarded against XSS injection.
When I try a url like:
https://www.clientsite.com?somekey=%3Csvg%20onload%3Dalert(document.cookie)%3E
on their site, I indeed get the alert panel displaying the cookies.
But when I run our script locally, I cannot reproduce this injection. The alert panel never shows up, no matter what I put in the query param's value.
A very simplified version of the script is:
<html lang="en">
<head>
<meta charset="utf-8">
<title>XSS test</title>
</head>
<body>
<div id="content"></div>
<script>
(function() {
var url = window.location.href
var someKey = 'somekey'
var regexS = "[\\?&]"+someKey+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
var parentElement = document.querySelector('#content');
var widget = document.createElement('div');
// var svgInjection = '<svg onload=alert("alert!!")>'
// var svgEncodedInjection = '%3Csvg%20onload%3Dalert("alert!!")%3E'
widget.innerHTML = '<div>' + results[1] + '</div>';
return parentElement.insertBefore(widget, parentElement.firstChild);
})()
</script>
</body>
</html>
I don't understand how an identical script, receiving identical query params, shows an alert panel on the client's site, and nothing when I run it locally. Any thoughts?

Unable to Consume Linkedin API through Localhost

I found similar threads but unfortunately didn't help resolve my issue so posting a new thread
I am trying to consume the linked API through localhost. The error I am getting is:
Uncaught Error: You must specify a valid JavaScript API Domain as part of this key's configuration.
Under Javascript Settings, Valid SDK Domains I added
http://127.0.0.1
http://127.0.0.1:8704
http://localhost
http://localhost:8704
http://localhost
I tried adding in https as well but still I am facing the same error.
I tried creating a ASP.NET project in Visual studio and tried running my html file with the associated port number which also I added in valid SDK domain, still the same issue.
My code is below:
<html>
<head>
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: [MY KEY] //Client ID
onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load
authorize: true
</script>
</head>
<script type="text/javascript">
function OnLinkedInFrameworkLoad() {
console.log('OnLinkedInFrameworkLoad');
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
console.log('OnLinkedInAuth');
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles) {
console.log('ShowProfileData' + profiles);
var member = profiles.values[0];
var id = member.id;
var firstName = member.firstName;
var lastName = member.lastName;
var photo = member.pictureUrl;
var headline = member.headline;
//use information captured above
var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: "
+ lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline
+ "<p/>"
document.getElementById('profiles').innerHTML = stringToBind;
}
</script>
<body>
<div id="profiles"></div>
</body>
</html>

How to send response with javascript to draw html elements

I'm creating a script like twitter in which user just provide an id and all his/her tweets get loaded on site where the script inserted.
What I've done is
User should copy this code to load my widget
<a class="getStarted" data-getStartedID="123456789">Get Started App ID</a>
<script>
!function(d,s,id){
var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){
js=d.createElement(s);
js.id=id;
js.src=p+"://localhost/practices/js_practice/siteOpen.js";
fjs.parentNode.insertBefore(js,fjs);
}}(document,"script","getStarted-C");
My siteOpen.js is as below :
!function(d){
var a = d.getElementsByClassName('getStarted');
var x = document.getElementsByClassName("getStarted")[0].getAttribute("data-getStartedID");
var r = new XMLHttpRequest();
var appID = x;
r.open("POST", "openwebIndex.php", true);
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
r.setRequestHeader("Content-length", appID.length);
r.setRequestHeader("Connection", "close");
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
if(r.responseText.trim()==1){
return '<p>output to be draw on where script is pasted</p>';
if(console)console.info('Valid appID');
}
};
r.send('appID='+appID);
}(document);
i don't know what to do to send the response and load/draw my widget on user's website.
My response will be in html elements.
Please suggest me what should i do. I just stuck at this point.
EDIT
I'm getting object HTMLScriptElement when I alert js variable.
Just trying adding the html code in the body tag.
users html file
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
<script src="widget.js"></script>
Your widget.js
// var appId = d.getElementsByClassName('getStarted');
// process the app id and make the output here
var output = "<div>This is the content of the widget</div>";
document.body.innerHTML += output;
This will show the content in the users html file. If you have cross domain issue, use JSONP for resolving that.

How i can embed Outlook Web App into my site?

I want to embed Outlook Web App into my site. Show Calendar, mail, people screens directly on pages of my site. I tried to do it via iFrame, but it is forbidden. Is it possible at all?
Contrary to common belief, this is achievable.
There are more details in my blogpost (http://blog.degree.no/2013/06/owa-in-iframe-yes-its-possible/) but here's the code needed. If you run it in "light mode" (flag = 1) there are less issues and it works cross domain, but if you run it within the same domain (e.g. website running on yourdomain.com and your exchange server is running on mail.yourdomain.com) it works fine for "full mode" (flag = 0) as well:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<script>
function LoginToOWA(server, domain, username, password) {
var url = "https://" + server + "/owa/auth/owaauth.dll";
// flags 0 = full version, flags 1 = light weight mode
var p = { destination: 'https://' + server + '/exchange', flags: '1', forcedownlevel: '0', trusted: '0', isutf8: '1', username: domain + '\\' + username, password: password };
var myForm = document.createElement("form");
myForm.method = "post";
myForm.action = url;
for (var k in p) {
var myInput = document.createElement("input");
myInput.setAttribute("name", k);
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput);
}
document.body.appendChild(myForm);
myForm.submit();
document.body.removeChild(myForm);
}
</script>
<body onload="javascript:LoginToOWA('mail.someserver.com','yourdomain','yourusername#someserver.com','yourpassword');">
<img src="../../gfx/loadingAnim.gif" /> Please wait while your inbox is loading...
</body>
</html>
Which version of OWA are you having? I have done this before for our company's intranet on OWA-2003. Just point your iframe to the webpart url like this:
http://server/exchange/user/inbox/?cmd=contents&view=Two-Line%20View&theme=4
This will work only if your main website uses Windows Integrated Authentication. You have to replace "user" with the logged in username using ASP.Net server-side code.
Search MS KB articles for the webpart parameters. You can show inbox, calendar etc.

Javascript - Reading file in client directory

I'm a new programmer that learn javascript, Im new in js actually.
I have a task that require a web page able to read file in client directory. I've got some js code :
<html>
<script type="text/javascript">
function ReadWeight() {
var filePath = "file:///D:/Text.txt";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",filePath,false);
xmlhttp.send(null);
var fileContent = xmlhttp.responseText;
alert(fileContent);
}
ReadWeight();
</script>
<body>
</body>
</html>
When I save this code in my directory and access it by this link, It works well.
file:///D:/test.html
But when I put it in my localhost and I access it, the JS doesn't works.
Does my code incorrect when in web server?
Please help me out.
Might I suggest using an error console to display the error so people know how to help you? =] And paste it in your query
Download something like firebug and see if a request is being made (for FireFox)
It looks like you would rather want to access the file via the http:// protocol, instead of file://
As far as I know you can only read client files using an <input type="file"> element. Once you get the file you can read it multiple times:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Refresh</title>
<script src="filerefresh.js"></script>
</head>
<body>
<input id="fileInput" type="file">
<pre id="fileDisplay"></pre>
</body>
</html>
JavaScript:
(function() {
var sleepInterval = 1000; // 1 second
var fileInput;
var fileDisplay;
var reader;
var id = undefined;
function initialize() {
fileInput = document.getElementById("fileInput");
fileDisplay = document.getElementById("fileDisplay");
reader = new FileReader();
reader.onloadend = function() {
fileDisplay.innerHTML = reader.result;
reschedule();
};
fileInput.addEventListener("change", readFile);
}
function reschedule() {
if (id !== undefined) {
clearTimeout(id);
}
id = setTimeout(readFile, sleepInterval);
}
function readFile() {
reader.readAsText(fileInput.files[0]);
}
window.onload = initialize;
})();

Categories

Resources