Weird behavior from Express, Socket.io chat app - html

I am attempting to create a chat app using socket.io on nodeJS and I want to add image transmission using the method outlined here
I'm running into an issue where if the image file is any larger than ~1MB, it seems to reset the connection and the io connection event is raised again (as the chat log gets re-sent).
Here is my code:
CLIENTSIDE
<html>
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Socket.IO chat</title>
<style>
body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
#form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 5rem; box-sizing: border-box; backdrop-filter: blur(10px); }
#input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
#input:focus { outline: none; }
#form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }
#subBtn {background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; margin-bottom:5.3rem;bottom: 0; left: 200; right: 0; display: flex; height: 2rem; box-sizing: border-box; backdrop-filter: blur(10px);}
#img {background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; margin-bottom:5.3rem;bottom: 0; left: 200; right: 0; display: flex; height: 2rem; box-sizing: border-box; backdrop-filter: blur(10px);}
#nametag {background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed;margin-top:-0.05rem;top: 0; left: 0; right: 0; display: flex; height: 2rem; box-sizing: border-box; backdrop-filter: blur(10px);}
#messages { list-style-type: none; margin-bottom: 2rem; padding: 0; }
#messages > li { padding: 1rem 1rem; font-size:30px; }
#messages > li:nth-child(odd) { background: #efefef; }
</style>
</head>
<body>
<div id="loginPrompt" style="position:fixed; margin:0;margin-top:-1rem; background-color:blue;width:100%;height:100%;z-index:2;">
<h2 style="color:white;margin-left:0.2rem;">Enter your name: </h2>
<form id="formName" style="margin-left:0.2rem;">
<input id="inputName"><button>Submit</button>
</form>
</div>
<div id="imageDiv" style="position:absolute; margin-bottom:5rem; z-index:2;"></div>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" placeholder="Enter your message..."/><button>Send</button>
</form>
<input type="file" id="img" onchange="setImgSrc(this)" accept="image/*"/>
<input type="submit" id="subBtn" onclick="submitImg()"/>
<script src="/socket.io/socket.io.js"></script>
<p id="nametag"></p>
<script>
var socket = io.connect()
var src
var setImgSrc = (elm) => {
var fr = new FileReader()
fr.onload = () => (src = fr.result)
fr.readAsArrayBuffer(elm.files[0])
}
var submitImg = () => socket.emit('submitImg',src)
socket.on('sentImg', (src) => {
// Create Img...
var img = document.createElement('img')
img.src = (window.URL || window.webkitURL).createObjectURL(
new Blob([src], {
type: 'image/png'
})
)
img.width = 300
img.height = 300
//sleep(5000)
var theDiv = document.createElement('div')
theDiv.append(img)
document.getElementById('messages').append(theDiv)
//var usern = document.getElementById('nametag')
//socket.emit('chat message', "(Photo from " + usern.innerHTML + ")")
})
var username = ""; //prompt("Please enter a username: ", "");
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
var formName = document.getElementById('formName');
var inputName = document.getElementById('inputName');
formName.addEventListener('submit', function (k) {
k.preventDefault();
if (inputName.value)
{
username = inputName.value;
nametag.innerHTML = username;
$('#loginPrompt').hide();
$('#form').attr('style', '');
//form.width = "100%";
socket.emit('chat message', username + ' has joined!');
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', username + ': ' + input.value);
input.value = "";
$('#input').attr('placeholder', 'Enter your message...');
}
if (inputName.value != "Enter your name..."){
name = inputName.value;
}
});
//return false;
}
});
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
</body>
</html>
SERVERSIDE JS:
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3001;
var chatlog = [];
app.use((req, res, next) => {
res.set('Cache-Control', 'no-store')
next()
})
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
for (i = 0; i < chatlog.length; i++){
io.emit('chat message', chatlog[i]);
}
socket.on('chat message', msg => {
chatlog.push(msg);
io.emit('chat message', msg);
});
socket.on('submitImg', (src) => {
console.log('Client sent image')
//Client submit an image
io.emit('sentImg', src) //the server send the image src to all clients
});
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
});
When I try to append the image to any element, if the file is small enough it'll work, if not, it'll just re-send the chat log as though a complete reconnect occurred.
I'm assuming the issue is that the data stream upload for the photo is not happening fast enough, and other code is executing prematurely. I employed a wait function and threw a whopping 5s delay in, but I still had the same issue. What's worse is the wait would only actually fire on the filesizes that would've worked anyway.
Any help would be greatly appreciated!!

I found the answer.
I simply need to change the max buffer filesizes as described in socket.io disconnects due to the size of data

Related

How to give some space between my buttons

I need help giving my buttons some space. No matter what I try, I just can't seem to space them out.
You can see my github repository here.
The following is my HTML with stylesheets inside.
<script src="update.js"></script>
<script src="sw.js"></script>
<script>
let d = new Date();
//alert(d);
let hrs = d.getHours();
let min = d.getMinutes();
let day = d.getDay();
let auth = false;
fetch('https://raw.githubusercontent.com/AzlanCoding/iframe-browser-pwa/main/lock.js')
.then(response => response.text())
.then(data => {
let split_str = "/split/";
const data_arr = data.split(split_str);
let lock = data_arr[1];
if (data_arr[0] === "lock") {
setInterval(lock,500);
}else{
alert(data_arr[0]);
}
console.log(data_arr[0]);
});
</script>
<!DOCTYPE html>
<html lang="en">
<style>
body {
background-color: ##2C2F33;
}
</style>
<head>
<meta name="theme-color" content="#2C2F33">
<meta charset="UTF-8">
<meta name="description" content="Azlan's iframe Browser">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0, no-store">
<!meta http-equiv="cache-control" content="max-age=0" />
<!meta http-equiv="Pragma" content="no-cache">
<!meta http-equiv="Expires" content="0">
<title> Iframe Browser </title>
<link rel="canonical" href="https://azlancoding.github.io/iframe-browser-pwa/" />
<link rel="manifest" href="/iframe-browser-pwa/manifest.webmanifest">
<meta name="keywords" content="bypass, school, browser in website, cloud browser">
<link rel="stylesheet" href="css/styles.css">
<title> iFrame browser </title>
<script language="javascript">
const getValidUrl = (url = "") => {
let newUrl = window.decodeURIComponent(url);
newUrl = newUrl.trim().replace(/\s/g, "");
if(/^(:\/\/)/.test(newUrl)){
return `https${newUrl}`;
}
if(!/^(f|ht)tps?:\/\//i.test(newUrl)){
return `https://${newUrl}`;
}
return newUrl;
};
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;
}
function getCookie(c_name){
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1){
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1){
c_value = null;
}
else{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1){
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
checkSession();
function checkSession(){
var c = getCookie("visited");
if (c === "yes") {
alert("Welcome back! Make sure you have your extension on.");
}
else {
alert("By continuing, you agree to the terms and conditions in azlancoding.github.io/iframe-browser/TermsAndConditions")
ext_install();
}
}
function ext_install()
{
if (window.confirm('An extension is required for this website to work. Do you want to install it now?'))
{
setCookie("visited", "yes", 365)
window.location.href='https://chrome.google.com/webstore/detail/ignore-x-frame-headers/gleekbfjekiniecknbkamfmkohkpodhe';
};
};
function checkCookie() {
let user = getCookie("alerted");
if (user != "") {
alert("Welcome again !");
} else
{ext_install();}
}
//document.getElementById("myIframe").src = "https://wwf.org";
var iframe = document.getElementById("myIframe");
//var website = iframe.src;
//console.log(website);
document.addEventListener("scroll", function(event)
{
var style = document.getElementById("myIframe").style;
style.webkitTransform = style.webkitTransform ? "" : "scale(1)";
})
/*function resizeIframe()
{
document.getElementById('myIframe').height = 100%;
}*/
function ResetBox()
{
if(document.getElementById("URL").value == '')
{document.getElementById("URL").value='';};
}
function LoadPage()
{
var objFrame=document.getElementById("myIframe");
var newurl = getValidUrl(document.getElementById("URL").value);
objFrame.src = newurl;
}
var elem = document.documentElement
function openFullscreen() {
if (elem.requestFullscreen)
{
elem.requestFullscreen();
}
else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
}
}
function closeFullscreen() {
if (document.exitFullscreen)
{
document.exitFullscreen();
}
else if (document.webkitExitFullscreen)
{
document.webkitExitFullscreen();
}
else if (document.msExitFullscreen)
{
document.msExitFullscreen();
}
}
</script>
<style>
.iframe-container {
overflow: visible;
/* 16:9 aspect ratio */
//padding-top: 56.25%;
position: 60px 0px;
//margin-top: 60px;
}
:root {
--fallback-title-bar-height: 45px;
}
.draggable {
app-region: drag;
/* Pre-fix app-region during standardization process */
-webkit-app-region: drag;
}
.nonDraggable {
app-region: no-drag;
/* Pre-fix app-region during standardization process */
-webkit-app-region: no-drag;
}
#child {
width: window.innerWidth;
//height: window.innerHeight;
height: 100vh;
flex: 1 1 auto;
position: absolute;
top: env(titlebar-area-height, var(--fallback-title-bar-height));
left: 0;
right: 0;
}
.button {
background-color: #ffffff;
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 10px;
margin: 4px 2px;
margin-right: 5px;
cursor: pointer;
border-radius: 10px;
app-region: no-drag;
/* Pre-fix app-region during standardization process */
-webkit-app-region: no-drag;
}
fieldset {
border: 0px;
}
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
}
#titleBarContainer {
position: absolute;
top: 0;
left: 0;
height: env(titlebar-area-height, var(--fallback-title-bar-height));
width: 100%;
background-color:#254B85;
}
#titleBar {
position: absolute;
top: 0;
display: flex;
user-select: none;
height: 100%;
left: env(titlebar-area-x, 0);
//left : 0px;
width: env(titlebar-area-width, 50%);
color: #FFFFFF;
font-weight: bold;
text-align: center;
}
#titleBar > span {
margin: 5;
padding: 0px 32px 0px 32px;
}
#titleBar > input {
flex: 1;
margin: 0px;
border-radius: 5px;
border: none;
padding: 8px;
}
#mainContent {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: env(titlebar-area-height, var(--fallback-title-bar-height));
overflow-y: scroll;
}
</style>
</head>
<body style="background-color:#254B85">
<div id="titleBarContainer" >
<div id="titleBar">
<span class="draggable">Iframe Browser</span>
<input class="nonDraggable" type="text" ID="URL" placeholder="Enter a URL" value="https://www.google.com"></input>
<input type="submit" class="frmSubmit" value="Go" onclick="LoadPage()">
<input type="button" VALUE="&#65513" onClick="history.back()">
<input type="button" VALUE="&#65515" onClick="history.forward()">
<input type="button" class="fullscreen" value="⛶" onclick="openFullscreen()">
<input type="button" class="Exitfullscreen" value="Exit Fullscreen" onclick="closeFullscreen()">
<input type="button" class="newWindow" value="New Window" onclick=" window.open('https://azlancoding.github.io/iframe-browser-pwa/','_blank')">
<input type="button" class="cloudbrowser" value="Cloud Browser" onclick="window.open('https://replit.com/#azlancoding/free-and-unlimited-cloud-browser?embed=true','_blank')">
</div>
</div>
<!div style="Clear:both;">
<!input type="text" value="https://www.google.com" class="frmUrlVal" ID="URL" placeholder = "Enter a URL" >
<!/div>
<div id = "child" >
<iframe align="top" width="100%" height="100%" allowtransparency="true" style="background: #FFFFFF;" src="https://www.google.com" onload = "check()" onerror"ext_install()" allow="camera;microphone" frameborder=yes loading ="lazy" name="myIframe" id="myIframe"> </iframe>
</div>
<script>
window.onbeforeunload = () => '';
var urlbox = document.getElementById("URL");
urlbox.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
LoadPage();
}
});
function check(){
document.getElementById("URL").value = "";
}
</script>
<script>
if (navigator.serviceWorker) {
navigator.serviceWorker.register (
'/iframe-browser-pwa/sw.js',
{scope: '/iframe-browser-pwa/'}
)
}
</script>
<script src="js/app.js"></script>
</body>
</html>
The stylesheet may be weird as it is used to support Windows Overlay Controls which allowed buttons to be placed on top next to the buttons to minimise, maximise and close the window. I just changed the manifest to support tabbed experimental feature.
Any help is appreciated.
Update:
I tried to use <span> but it over did it...

Microsoft BotFramework-WebChat scrolling issues

I'm using the microsoft/BotFramework-WebChat, but I'm having problems getting it to scroll properly.
Often when the bot responds the user is forced to manually scroll to the bottom of the chat log.
I can't find any documentation about hooks that would let me call an API to scroll it.
Is there a way to get it so that the chat window scrolls automatically?
HTML:
<div id="bot-button" style="display:none" >
<p id="need-help" class="triangle-isosceles">Hey! Need any help?</p>
<div id="bot-open" token="temptoken">
<span>
<img id="avatar" src="/img/avatar.png"/>
<i id="message-count">2</i>
</span>
</div>
<div id="bot-close"><img src="/img/close.png" height="20px"/>Close</div>
<div id="webchat" role="main"></div>
</div>
<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
<script src="/js/chat.js"></script>
JavaScript:
(async function () {
// In this demo, we are using Direct Line token from MockBot.
// To talk to your bot, you should use the token exchanged using your Direct Line secret.
// You should never put the Direct Line secret in the browser or client app.
// https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
var bearer_token = document.getElementById("bot-open").getAttribute("token");
const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', {
method: 'POST',
headers: {
"Authorization": "Bearer " + bearer_token
}
});
const {
token
} = await res.json();
// We are using a customized store to add hooks to connect event
const store = window.WebChat.createStore({}, ({
dispatch
}) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
// When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: {
language: window.navigator.language
}
}
});
}
return next(action);
});
const styleOptions = {
bubbleBackground: 'rgba(0, 0, 255, .1)',
bubbleFromUserBackground: 'rgba(0, 255, 0, .1)',
hideUploadButton: true,
botAvatarInitials: 'DA',
};
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({
token
}),
userID: guid(),
store,
styleOptions
}, document.getElementById('webchat'));
sizeBotChat();
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
function sizeBotChat() {
let bot_container = document.getElementById("bot-button");
if (isMobileDevice()) {
bot_container.style.width = "100%";
bot_container.style.bottom = "0px";
bot_container.style.right = "0px";
let max_height = screen.height - 50;
document.getElementById("webchat").style.maxHeight = max_height + "px";
console.log(screen.height);
} else {
bot_container.style.width = "400px";
bot_container.style.right = "50px";
document.getElementById("webchat").style.maxHeight = "400px";
}
}
CSS (loaded by javascript inserting a link into the head element):
.triangle-isosceles {
position: relative;
padding: 15px;
color: black;
background: white;
border-radius: 10px;
}
/* creates triangle */
.triangle-isosceles:after {
content: "";
display: block;
/* reduce the damage in FF3.0 */
position: absolute;
bottom: -15px;
right: 30px;
width: 0;
border-width: 15px 15px 0;
border-style: solid;
border-color: white transparent;
}
#avatar {
height: 50px;
}
#need-help {
display: none;
}
/* based on badge progress-bar-danger from bootstrap */
#message-count {
display: inline-block;
min-width: 10px;
padding: 3px 7px 3px 7px;
font-size: 12px;
font-weight: 700;
line-height: 1;
color: white;
text-align: center;
white-space: nowrap;
vertical-align: middle;
border-radius: 10px;
background-color: #d9534f;
position: relative;
top: -20px;
right: 20px;
}
#bot-button {
position: fixed;
bottom: 50px;
right: 0px;
width: 100%;
}
#bot-open {
height: 50px;
width: 100%;
text-align: right;
}
#bot-close {
background-color: blue;
background-image: url("https://localhost/img/avatar.png");
background-repeat: no-repeat;
color: white;
height: 22px;
display: none;
height: 50px;
padding: 15px 15px 0 0;
text-align: right;
vertical-align: middle;
}
/* hide chat on load */
#webchat {
display: none;
max-height: 400px;
overflow: scroll;
}
#webchat div.row.message {
margin: 0;
}
The developers designed WebChat to scroll the conversation to the bottom if the user hasn't scrolled up. If the user has scrolled up, there should be a 'New Message' button that appears in the bottom right corner of the chat when the bot sends a new message.
You can modify this behavior by using a custom middleware - which it looks like you already are - and scrolling the last element in the conversation into view when the user receives a message from the bot. See the code snippet below.
const store = window.WebChat.createStore(
{},
({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
document.querySelector('ul[role="list"]').lastChild.scrollIntoView({behavior: 'smooth', block: 'start'});
}
...
return next(action);
}
);
Hope this helps!

How to integrate a script into a function in HTML?

I want to make a html button that appears when you scroll down and when clicked it shows a random blogger post.
I have code to make it appear when you scroll down and code for a button that shows a random post. But I don't know how to make them work together.
This is my scroll button code, below is random post code. I don't know how to integrate it inside TopFunction.
Thank you very much for your help and insights!
#myBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#myBtn:hover {
background-color: #555;
}
</style>
<button onclick="topFunction()" id="myBtn"></button>
<script>
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// When the user clicks on the button, show random post
function topFunction() {
}
</script>
RANDOM POST
<script type="text/javascript">
function showLucky(root){ var feed = root.feed; var entries = feed.entry || []; var entry = feed.entry[0]; for (var j = 0; j < entry.link.length; ++j){if (entry.link[j].rel == 'alternate'){window.location = entry.link[j].href;}}} function fetchLuck(luck){ script = document.createElement('script'); script.src = '/feeds/posts/summary?start-index='+luck+'&max-results=1&alt=json-in-script&callback=showLucky'; script.type = 'text/javascript'; document.getElementsByTagName('head')[0].appendChild(script); } function feelingLucky(root){ var feed = root.feed; var total = parseInt(feed.openSearch$totalResults.$t,10); var luckyNumber = Math.floor(Math.random()*total);luckyNumber++; a = document.createElement('a'); a.href = '#random'; a.rel = luckyNumber; a.onclick = function(){fetchLuck(this.rel);}; a.innerHTML = 'RANDOM POST'; document.getElementById('myBtn').appendChild(a); } </script><script src="/feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky">
</script>
I have no idea if below is correct or not. In order to help you correctly we need to know WHERE the codes are coming from. And you need to explain into detail what you have tried.
Below might work: I have added a <div> for which should contain the random posts when button is clicked. Content can be styled as you wish.
Be aware of the path /feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky. This is hardcoded and the JS script change some word in it. This needs to be the same (and the one in the code) to your own folderstructure.
I have also cleared up your code a little... Always use id for scripts and class for CSS styling.
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// When the user clicks on the button, show random post
function topFunction() {
//Why is this empty?
};
function showLucky(root) {
var feed = root.feed;
var entries = feed.entry || [];
var entry = feed.entry[0];
for (var j = 0; j < entry.link.length; ++j) {
if (entry.link[j].rel == 'alternate') {
window.location = entry.link[j].href;
}
}
};
function fetchLuck(luck) {
script = document.createElement('script');
script.src = '/feeds/posts/summary?start-index=' + luck + '&max-results=1&alt=json-in-script&callback=showLucky';
script.type = 'text/javascript';
document.getElementsByTagName('randompost')[0].appendChild(script);
}
function feelingLucky(root) {
var feed = root.feed;
var total = parseInt(feed.openSearch$totalResults.$t, 10);
var luckyNumber = Math.floor(Math.random() * total);
luckyNumber++;
a = document.createElement('a');
a.href = '#random';
a.rel = luckyNumber;
a.onclick = function() {
fetchLuck(this.rel);
};
a.innerHTML = 'RANDOM POST';
document.getElementById('myBtn').appendChild(a);
};
.myBtn {
display: block;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
.myBtn:hover {
background-color: #555;
}
.myDiv {
width: 50%;
height: auto;
background: rgba(255,0,0,0.5);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="showLucky()" id="myBtn" class="myBtn">Try me</button>
<div class="myDiv" id="randompost" >
<script src="/feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky">
</script>
Something here...
</div>

How to display additional information in Google Maps autocomplete suggestions?

I am using Google Places autocomplete to select cities by name. Currently it displays only the city name and the country it belongs to, in the suggestions drop down.
I have checked and found that the "address_components" object, that gets populated when a city is selected, has additional attibutes like state/province and other parts of the address. So, it is clear that the Google's API provide additional information other than merely the city and country names.
What I am trying to achieve is, displaying a couple of those additional data in the suggestions dropdown.
Is there a way to do that?
(I have marked on the screenshot where I need to display the additional attributes)
Here is the code.
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initAutocomplete&query=locality" async defer></script>
<script>
var searchBox;
function initAutocomplete() {
var options = {types: ['(cities)']};
var input = document.getElementById('placeAuto');
searchBox = new google.maps.places.Autocomplete(input);
searchBox.addListener('place_changed', fillInAddress);
}
function fillInAddress()
{
var place = searchBox.getPlace();
console.log(place);
}
</script>
As I commented already, you can do that by using the Autocomplete and Places services and the getPlacePredictions method, but I would not recommend this approach as it will make a high number of requests to the API (one for each result, each time a user types something in the address field).
View the snippet in full screen mode as it won't fit hereunder or check it on JSFiddle.
In this example I have added the place latitude and longitude in the autocomplete results.
var autocompleteService, placesService, results, map;
function initialize() {
results = document.getElementById('results');
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(50, 50)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Bind listener for address search
google.maps.event.addDomListener(document.getElementById('address'), 'input', function() {
results.style.display = 'block';
getPlacePredictions(document.getElementById('address').value);
});
// Show results when address field is focused (if not empty)
google.maps.event.addDomListener(document.getElementById('address'), 'focus', function() {
if (document.getElementById('address').value !== '') {
results.style.display = 'block';
getPlacePredictions(document.getElementById('address').value);
}
});
// Hide results when click occurs out of the results and inputs
google.maps.event.addDomListener(document, 'click', function(e) {
if ((e.target.parentElement.className !== 'pac-container') && (e.target.parentElement.className !== 'pac-item') && (e.target.tagName !== 'INPUT')) {
results.style.display = 'none';
}
});
autocompleteService = new google.maps.places.AutocompleteService();
placesService = new google.maps.places.PlacesService(map);
}
// Get place predictions
function getPlacePredictions(search) {
autocompleteService.getPlacePredictions({
input: search,
types: ['geocode']
}, callback);
}
// Place search callback
function callback(predictions, status) {
// Empty results container
results.innerHTML = '';
// Place service status error
if (status != google.maps.places.PlacesServiceStatus.OK) {
results.innerHTML = '<div class="pac-item pac-item-error">Your search returned no result. Status: ' + status + '</div>';
return;
}
// Build output for each prediction
for (var i = 0, prediction; prediction = predictions[i]; i++) {
// Get place details to inject more details in autocomplete results
placesService.getDetails({
placeId: prediction.place_id
}, function(place, serviceStatus) {
if (serviceStatus === google.maps.places.PlacesServiceStatus.OK) {
// Create a new result element
var div = document.createElement('div');
// Insert inner HTML
div.innerHTML += '<span class="pac-icon pac-icon-marker"></span>' + place.adr_address + '<div class="pac-item-details">Lat: ' + place.geometry.location.lat().toFixed(3) + ', Lng: ' + place.geometry.location.lng().toFixed(3) + '</div>';
div.className = 'pac-item';
// Bind a click event
div.onclick = function() {
var center = place.geometry.location;
var marker = new google.maps.Marker({
position: center,
map: map
});
map.setCenter(center);
}
// Append new element to results
results.appendChild(div);
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
body,
html {
font-family: Arial, sans-serif;
padding: 0;
margin: 0;
height: 100%;
}
#map-canvas {
height: 150px;
margin-bottom: 5px;
}
table {
border-collapse: collapse;
margin-left: 20px;
}
table td {
padding: 3px 5px;
}
label {
display: inline-block;
width: 160px;
font-size: 11px;
color: #777;
}
input {
border: 1px solid #ccc;
width: 170px;
padding: 3px 5px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-shadow: 0 2px 6px rgba(0, 0, 0, .1);
}
.pac-container {
background-color: #fff;
z-index: 1000;
border-radius: 2px;
font-size: 11px;
box-shadow: 0 2px 6px rgba(0, 0, 0, .3);
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
overflow: hidden;
width: 350px;
}
.pac-icon {
width: 15px;
height: 20px;
margin-right: 7px;
margin-top: 6px;
display: inline-block;
vertical-align: top;
background-image: url(https://maps.gstatic.com/mapfiles/api-3/images/autocomplete-icons.png);
background-size: 34px;
}
.pac-icon-marker {
background-position: -1px -161px;
}
.pac-item {
cursor: pointer;
padding: 0 4px;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
line-height: 30px;
vertical-align: middle;
text-align: left;
border-top: 1px solid #e6e6e6;
color: #999;
}
.pac-item:hover {
background-color: #efefef;
}
.pac-item-details {
color: lightblue;
padding-left: 22px;
}
.pac-item-error,
.pac-item-error:hover {
color: #aaa;
padding: 0 5px;
cursor: default;
background-color: #fff;
}
<div id="map-canvas"></div>
<table>
<tr>
<td>
<label for="address">Address:</label>
</td>
</tr>
<tr>
<td>
<input id="address" placeholder="Enter address" type="text" tabindex="1" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="results" class="pac-container"></div>
</td>
</tr>
</table>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

Get user media api not working in local host

i am exploring the API of the get user media and tried running the api in my localhost with sample code attached below
It is working fine in jsbin here
but completely fails in localhost with below errors
Uncaught TypeError: Cannot read property 'addEventListener' of null capture.html:43
Uncaught TypeError: Cannot set property 'src' of null
Code :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script>
(function() {
var streaming = false,
video = document.querySelector('#video'),
cover = document.querySelector('#cover'),
canvas = document.querySelector('#canvas'),
photo = document.querySelector('#photo'),
startbutton = document.querySelector('#startbutton'),
width = 200,
height = 0;
navigator.getMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
navigator.getMedia(
{
video: true,
audio: false
},
function(stream) {
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
} else {
var vendorURL = window.URL || window.webkitURL;
video.src = vendorURL ? vendorURL.createObjectURL(stream) : stream;
}
video.play();
},
function(err) {
console.log("An error occured! " + err);
}
);
video.addEventListener('canplay', function(ev){
if (!streaming) {
height = video.videoHeight / (video.videoWidth/width);
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
}
}, false);
function takepicture() {
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(video, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
}
startbutton.addEventListener('click', function(ev){
takepicture();
ev.preventDefault();
}, false);
})();
</script>
<style>
html {
background: #111111;
height: 100%;
background: linear-gradient( #333, #000);
}
canvas {
display: none;
}
video, img, #startbutton {
display: block;
float: left;
border: 10px solid #fff;
border-radius: 10px;
}
#startbutton {
background: green;
border: none;
color: #fff;
margin: 100px 20px 20px 20px;
padding: 10px 20px;
font-size: 20px;
}
#container {
overflow: hidden;
width: 880px;
margin: 20px auto;
}
</style>
</head>
<body>
<video id="video"></video>
<button id="startbutton">Take photo</button>
<canvas id="canvas"></canvas>
<img src="http://placekitten.com/g/200/150" id="photo" alt="photo">
</body>
</html>
It is because your script is trying to access html elements that have not been created yet. HTML is read from the top down. Move your script into the body of your page, or tell it not to execute until the whole page loads.
It worked fine for me when I moved your script to the body instead of the head of the page.