Is there a way to set a JS eventlistener on the state of the Oculus or Gear VR proximity sensor? My goal is to detect when someone has removed the headset? This will be used to trigger a reset of the web app to its initial state, ready for the next user. For instance, it might call location.reload().
The proximity sensor is not available to web pages as far as I know.
Does your scenario happen in the browser without opening new tabs? You could use the page visibility API:
<!DOCTYPE html>
<script>
document.addEventListener('visibilitychange', (e) => {
document.body.append(Date() + ' head set is ' + (document.hidden ? 'off' : 'on'));
document.body.append(document.createElement('br'));
});
</script>
Related
I am trying to get users interactions in google map (zoom in/out, map changed) that is embedded with iframe in my website. I read lots of articles for submiting Forms, but with iframe maps, could not find a way. Which is the right trigger, in order to accoplish that?
For now, I have created a custom HTML tag that has this kind of code:
<script>
try {
var postObject = JSON.stringify({
event: 'mapChanged',
});
parent.postMessage(postObject, 'https://www.example.com/contact/');
} catch(e) {
window.console && window.console.log(e);
}
</script>
and a trigger that has this options:
Page View and Page URL equals to: https://www.example.com/contact/
Because of the trigger I could see the tag in GTM, but of course this is not correct.. I do not want to trigger every time a user visit the contact page, but when clicks on the map or zoom in/out
I have a javascript code that checks whether there are some people connected to a room in Twilio Programmable Video. If there are any participants, the javascript adds their remote video to the webpage.
// A function that adds a remote participant audio & video to the current web page.
function AddParticipantAudioAndVideo(participant) {
participant.tracks.forEach(publication => {
if (publication.track) {
document.getElementById("some html item").appendChild(track.attach());
console.log("track subscribed");
}
});
participant.on('trackSubscribed', track => {
document.getElementById("some html item").appendChild(track.attach());
console.log('track subscribed');
});
}
function InitializeRoom() {
// room is defined somewhere else
room.on('participantConnected', participant => {
console.log('A remote Participant connected : ' + participant.identity);
AddParticipantAudioAndVideo(participant);
});
// Loop over all the participants already connected to the room
room.participants.forEach(participant => {AddParticipantAudioAndVideo(participant)});
}
If I call this code from a button click for example, it works and live video plays properly :
<div onclick="InitializeRoom()">My Button</div>
However if I call the exact same code from the page load event handler (before any manual interaction with the page), it doesn't work and the video tag is not added to the html document.
window.addEventListener("load",function(event){
InitializeRoom();
});
I know that Chrome doesn't like videos with audio and autoplay = true. So I was wondering if this problem is due to the same reason and if there is any solution to that.
Thanks
Cheers,
I know that Chrome doesn't like videos with audio and autoplay = true. So I was wondering if this problem is due to the same reason and if there is any solution to that.
Yes, exactly.
Based on your other questions, I assume you're wanting to do this in some automated context where you have control over the browser. If so, you can add a flag to the Chrome/Chromium command line:
chrome.exe --autoplay-policy=no-user-gesture-required
See also: https://developer.chrome.com/blog/autoplay/#developer-switches
I would like to ask if it is possible to expand a Watson Assistant Chatbot on page load ? Currently, when the page loads, a user will then have to click on the little icon below to start the chatbot.
Watson Assistant Chatbot Icon
I am using Chrome, and the solution should also be working on mobile platforms.
I have the following empty page with the chatbot script so far :
<body style="height: 100%;">
<script src=https://assistant-web.watsonplatform.net/loadWatsonAssistantChat.js></script>
<script>
window.loadWatsonAssistantChat({
integrationID: "some id", // The ID of this integration.
region: "eu-gb" // The region your integration is hosted in.
}).then(function(instance){
instance.render();
});
</script>
</body>
</html>
Looking above I notice that you are using the new IBM Web Chat client, which is added to your html page. If you notice in the documentation for the web client - there is the section about extending the web chat and the extra documentation in GitHub.
In that documentation you will find a list of extra options that can be added to the creation of your instance of Web Chat. One of those options is to have the Web Chat open on loading the web page, rather than the icon. Or even adding the web chat to your own icon.
The option you are after is;
options.openChatByDefault - boolean - Optional - false - Whether to render the chat window initially in an open state. By default, the chat window is rendered in a closed state.
So your code should be;
<body style="height: 100%;">
<script src=https://assistant-web.watsonplatform.net/loadWatsonAssistantChat.js></script>
<script>
window.loadWatsonAssistantChat({
integrationID: "some id", // The ID of this integration.
region: "eu-gb", // The region your integration is hosted in.
options.openChatByDefault: true
}).then(function(instance){
instance.render();
});
</script>
</body>
</html>
Acording to the API you need openChatByDefault: true within window.watsonAssistantChatOptions = {...}.
Mind that my version of the API at the time of answering is different than that of the question, it goes with the following script for the embed.
window.watsonAssistantChatOptions = {
integrationID: "############", // The ID of this integration.
region: "eu-gb", // The region your integration is hosted in.
serviceInstanceID: "############", // The ID of your service instance.
onLoad: function(instance) { instance.render(); },
openChatByDefault: true
};
setTimeout(function(){
const t=document.createElement('script');
t.src="https://web-chat.global.assistant.watson.appdomain.cloud/versions/" + (window.watsonAssistantChatOptions.clientVersion || 'latest') + "/WatsonAssistantChatEntry.js"
document.head.appendChild(t);
});
I am trying to find a way to count a number of tabs that are currently open in Chrome by javascript.
I have searched and found chrome.tabs.query(). But when I opened my console and tried it I got an undefined message.
Is it not supported anymore by Chrome, or can it only be used in extension development?
As wscourge has implied, chrome.tabs.query() is a Chrome extension API, which is only available to extensions, not web page JavaScript. In fact, it is only available in the background context of an extension (i.e. not content scripts).
To find the number of tabs that are open, you could do something like:
chrome.tabs.query({windowType:'normal'}, function(tabs) {
console.log('Number of open tabs in all normal browser windows:',tabs.length);
});
If you want to run this from a console, you will need to have an extension loaded that has a background page. You will then need to open the console for the background page. From that console, you can execute the above code.
I found the answer to this question here: https://superuser.com/questions/967064/how-to-get-tab-count-in-chrome-desktop-without-app-extension
Go to chrome://inspect/#pages
Run the following line of code in the javascript console:
document.getElementById("pages-list").childElementCount
The tabs count will be printed to the console.
Local and Session storage
In case when we want count only tabs witch our website - first on page load (open tab) event we generate tab hash and we save it in sessionStorage (not shared between tabs) and as key in TabsOpen object in localStorage (which is shared between tabs). Then in event page unload (close tab) we remove current tab hash (saved in sesionStorage) from TabsOpen in localStorage.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My project</title>
...
<script>
function tabLoadEventHandler() {
let hash = 'tab_' + +new Date();
sessionStorage.setItem('TabHash',hash);
let tabs = JSON.parse(localStorage.getItem('TabsOpen')||'{}');
tabs[hash]=true;
localStorage.setItem('TabsOpen',JSON.stringify(tabs));
}
function tabUnloadEventHandler() {
let hash= sessionStorage.getItem('TabHash');
let tabs = JSON.parse(localStorage.getItem('TabsOpen')||'{}');
delete tabs[hash];
localStorage.setItem('TabsOpen',JSON.stringify(tabs));
}
</script>
...
</head>
<body onunload="tabUnloadEventHandler()" onload="tabLoadEventHandler()">
...
</body>
</html>
Thanks to this in TabsOpen object in localStorage we have information about current open tabs which can be read by
let tabsCount = Object.keys( JSON.parse(localStorage.getItem('TabsOpen')||'{}') ).length
It can only be used in extension development.
You are not able to access that information from document level.
This is not a solution using javascript, but maybe it can help double-check the count against another solution. It is by far the easiest (one-click) solution that works for me:
If you have chrome sync enabled, simply navigate to chrome.google.com/sync
It should give you the count of open tabs, among other counts (e.g. bookmarks, extensions, etc)
I have the following JS to display the current user's Zipcode in #zip:
(function ($, geolocation) {
if (geolocation) {
geolocation.getCurrentPosition(function (position) {
$.getJSON(
"http://ws.geonames.org/findNearestAddressJSON?callback=?",
{
lat : position.coords.latitude,
lng : position.coords.longitude
},
function (data) {
$(function () {
$('#zip').text(data.address.postalcode);
});
}
);
});
}
}(jQuery, navigator.geolocation));
I also have a JS function to reload the page:
$('.reload').click(function(){
window.location.reload(true);
});
In Mobile Safari, these two functions work together well. If the user opens the webpage, it will load the user's current zipcode. Then, if the user changes locations, the user can reload the page by tapping the botton. This works fine, except when <meta name="apple-mobile-web-app-capable" content="yes"> is present.
When it is present, this what happens:
User taps the icon on their home screen
Webpage opens, with the address bar hidden, as <meta name="apple-mobile-web-app-capable" content="yes"> does this
Zipcode loads like it should
User moves location, taps the reload button
Page fails to show the zipcode, with no erros logged to the console
I'm really stuck on how to fix this, but if this helps at all, here's a working example:
http://www.codekraken.com/testing/zipper/zip.html
There is no reload in full-screen web apps (using apple-mobile-web-app-capable). However, when the user changes location, and then runs the app again, it will always load the page. It won't fire the reload event, but it will fire the onload event - every time it runs.
If the user leaves the app running and changes location, you'll need a simple "find me again" function that simply reruns your code to find the current location and zipcode.
Now - HERE is a catch! I've found that on iOS, the position is often cached, even if you tell it to only use a fresh location, so sometimes, you'll get the old location. I created a workaround for this called getAccurateCurrentLocation() that uses a very similar interface. You can find the code at https://github.com/gwilson/getAccurateCurrentPosition - it's very simple to drop in as a replacement to getCurrentPosition().
That should do it.
In case anyone else has confusion (as I had), the method involved here is the native "watchPosition" method of the geolocation object.
WatchPosition MDN Specs
The watchPosition method will be called when the user moves location, and you can specify your lat/long to zip generator as the callback.
From the specs:
var watchID = navigator.geolocation.watchPosition(function(position) {
do_something(position.coords.latitude, position.coords.longitude);
});
so it looks like you could do:
var watchID = navigator.geolocation.watchPosition(function(position) {
$.getJSON(
"http://ws.geonames.org/findNearestAddressJSON?callback=?",
{
lat : position.coords.latitude,
lng : position.coords.longitude
},
function (data) {
$(function () {
$('#zip').text(data.address.postalcode);
});
}
);
});
which will accomplish even more simplicity -- the user will not have to tap the location button, it should already be updated as they move.
To be clear, Greg's function uses this watchPosition method, but if you want to understand what is at work, or use the much leaner native code and customize it yourself, watchPosition is your tool.
Fullscreen mode launches the browser in a WebSheet which might have a separate set of geolocation permissions. Maybe previously you declined to share the geolocation information in a WebSheet but allowed it in the Safari browser.
And if I recall correctly, WebSheets are known to reset their permissions from time to time and prompt the user again to allow reading geolocations every few hours.