The main button of the Telegram web application does not work [closed] - javascript

Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 2 days ago.
Improve this question
I'm using Google Apps to write a telegram bot and a web app. In the Telegram app on IPhone, the code works fine except for the tg.sendData("string to send") method - the button is clicked but sendData doesn't fire, the sent message is "string to send" is not displayed in the bot. In the desktop version of Telegram on Windows, the MainButton button is not displayed at all. Also, the click event of the btn button does not work and, accordingly, the tg.MainButton.hide(), tg.MainButton.show() methods do not work.
Tell me, please, what could be the matter?
const webApps = `https://script.google.com/macros/s/**KEY**/exec?chatID=**CHAT_ID**`
const web_app_info = { url: webApps }
const KB_WEB_APP = {
keyboard: [
[{
text: "Моя кнопка",
web_app: web_app_info
}]
],
resize_keyboard: true,
one_time_keyboard: true
}
function botSendKeyboard(chat_id, text, keyboard = KB_WEB_APP) {
let data = {
method: "post",
payload: {
chat_id: String(chat_id),
text: text,
parse_mode: "HTML",
reply_markup: JSON.stringify(keyboard)
}
};
UrlFetchApp.fetch(tgAPI + "/sendMessage", data)
}
function doGet(e) {
let htmlOutput = HtmlService.createHtmlOutputFromFile('index1.html')
htmlOutput.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
return htmlOutput
}
Код index1.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Telegram WebApps</title>
<script src="https://telegram.org/js/telegram-web-app.js"></script>
</head>
<body>
<p>Заголовок</p>
<button id="btn" class="button">Show/Hide Main Button</button>
</body>
<script>
let tg = window.Telegram.WebApp;
tg.MainButton.text = "My Text";
tg.MainButton.show()
let btn = document.getElementById("btn");
btn.addEventListener('click', function(){
if (tg.MainButton.isVisible){
tg.MainButton.hide()
}
else tg.MainButton.show()
});
window.Telegram.WebApp.onEvent("mainButtonClicked", function(){
tg.sendData("some string that we need to send");
});
</script>
</html>

Related

I use .appendChild but after I refresh it is gone. How can I keep it there without using cookies? So multiple devices will see the same thing?

I am making a todo-list in javascript but whenever I add something into this list and then refresh, it is gone. How can I make it able to save, and I don't want to use cookies and would like to use this todo list across multiple devices with the todo list saving. For example, is there a way to add a container directly into my html instead of through my browser? I know of the .appendChild but that adds it only to the browser and it does not save. I need to do this without cookies.
Recreate this problem:
copy and paste the code below into a .html
open it up through your browser.
add a todo into the input box, for example "throw out the trash"
add a due date for this todo.
click the "Add Todo" button.
Refresh the page.
My code so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Practice </title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<input id="todo-title" type="text" />
<input id="date-picker" type="date" />
<button onclick="addTodo();">Add Todo</button>
<div id="todo-list"></div>
<script>
const todos = [{
title: 'Get groceries',
dueDate: '2021-10-04'
}, {
title: 'Wash car',
dueDate: '2021-02-03'
}, {
title: 'Make dinner',
dueDate: '2021-03-04'
}];
//todos.push('another todo'); //Adds to an array
render();
function addTodo(){
const textbox = document.getElementById('todo-title');
const title = textbox.value;
const datePicker = document.getElementById('date-picker');
const dueDate = datePicker.value;
todos.push({
title: title,
dueDate: dueDate
});
render();
}
function render(){
//reset list
document.getElementById('todo-list').innerHTML = '';
todos.forEach(function(todo){
const element = document.createElement('div');
element.innerText=todo.title + ' is due by ' + todo.dueDate;
const todoList = document.getElementById('todo-list');
todoList.appendChild(element);
});
}
//todos.pop(); //Remove's the last string of an array
</script>
<!--<div id="counter">0</div>
<button onclick="addCount();">Up</button>
<button onclick="removeCount();">Down</button> -->
<script src="script.js"></script>
</body>
</html>
I tried to make the todo-list save after refreshing. What resulted was the todo disappearing.

How do I get a user input and insert it into the api link is JavaScript? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=320, initial-scale=1">
<meta charset="utf-8">
<style>
body, html {
min-width: 100%;
min-height: 100%;
margin: 0;
padding: 0;
font: Arial 14px;
}
</style>
</head>
<body>
<p>
Enter GD Username:
</p>
<input id="bruh">
<script>
var bruh = document.getElementById("bruh").value;
const url = `https://example.com/api/${bruh}`;
async function getData() {
const response = await fetch(url);
const data = await response.json();
console.log(data);
}
</script>
<button onclick="getData()">
Try
</button>
</body>
</html>
Hey guys, right now I’m trying hard to make a system that can fetch data from an api from what the user types in. What I have done already is make the fetching work, and the variable works, but for some reason when I type in something in the input box, it doesn’t work. Anyone know why?
The problem is you click the button the bruh variable is already declared but not defined. so You need to have these 2 lines inside your function:
var bruh = document.getElementById("bruh").value;
const url = `https://example.com/api/${bruh}`;
So you final code should look like this:
<script>
async function getData() {
var bruh = document.getElementById("bruh").value;
const url = `https://example.com/api/${bruh}`;
const response = await fetch(url);
const data = await response.json();
console.log(data);
}
</script>
In your code you're getting the input value as soon as the DOM/website is loaded and it means that it's going to be empty. You have to get the input value inside the getData function when you press click.
Change the script to this:
<script>
async function getData() {
var bruh = document.getElementById("bruh").value;
const url = `https://example.com/api/${bruh}`;
const response = await fetch(url);
const data = await response.json();
console.log(data);
}
</script>
Every time you click the button the variable bruh need to be updated, thus the need to be inside the function. Otherwise every time you click it will send the same request as before.

Is there absolutely no way to have html forms not refresh the page after submit WITHOUT jQuery? [duplicate]

This question already has answers here:
Stop form submission with submit eventlistener
(3 answers)
Javascript onclick function is called immediately (not when clicked)? [duplicate]
(1 answer)
Closed 2 years ago.
So I am now working on learning node.js servers with socket.io, and having the form submitted would recreate a new web socket connection. I have read that it could be fixed using jQuery to alter the submit action of the form in order to not have it refresh the page, but right now I just want to see if it could be done without jQuery or AJAX.
my html looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<form id="form" onsubmit="" action="">
<input name="message" id="message" type="text" placeholder="message" autocomplete="off">
<input id="send" type="submit">
</form>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
where main.js :
const socket = io.connect('83.130.85.31:7776');
const button = document.getElementById("send");
const message = document.getElementById("message");
const form = document.getElementById("form");
const sendMessage = (event) => {
socket.emit("message", {message: message.value});
message.value = "";
};
form.addEventListener("submit", sendMessage)
socket.on("message", (data) => {
console.log(data.message);
})
I know my code is very naive, I just focus on understanding implementation of socket.io right now and it was a small test.
Use Event.preventDefault()
const sendMessage = (e) => {
e.preventDefault();
socket.emit("message", {message: message.value});
message.value = "";
};
button.addEventListener("click", sendMessage);
You can do the same thing with the form's submit handler:
form.addEventListener("submit", sendMessage);

How do I access a text to speech voice when I make a website ( for Edge browser)

When I run load the webpage below in Edge it tells me that 8 voices are available on my computer. But only 2 are operational voice[4] and voice[7]. In firefox there is only one available and operational, voice[0].
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>Speech synthesiser</title>
<script>
var synth = window.speechSynthesis;
function populateVoiceList() {
var voiceSelect = document.getElementById("voicesAvailable");
voiceSelect.innerHTML = '';
voices = synth.getVoices();
for(i = 0; i < voices.length ; i++) {
var option = document.createElement('option');
option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
voiceSelect.appendChild(option);
}
}
</script>
</head>
<body onload="populateVoiceList()">
<h1>speech test 1</h1>
<form id="myForm">
<select id="voicesAvailable">
<option>Choose a voice</option>
</select>
</form>
</body>
</html>
In Microsoft Edge browser there seems to be a geographic filter being applied to restrict the voices. So, while 8 names get placed in the drop-down box only 2 actually are available. How do I modify the program so that I only load the voices which will work on the computer?
Any advice appreciated.
Thanks
New Edit..
I found a related question containing a response from Islam Elshobokosy. He submitted this code snippet:
speechSynthesis.onvoiceschanged = function() {
var voices = this.getVoices();
console.log(voices);
};
When I clicked the associated button on the Stack Overflow page to run that code it produced a result that revealed the only two functioning voices on my computer. It did not give the other 6.
My question is now:
1. How is this code filtering out the 6 irrelevant voices that my webpage page (above) is finding?
2. How do I incorporate something like this into my webpage?

JSON data not returned from Azure blob storage query

I'm in the process of trying to create a quiz using JavaScript and JQuery. I'm storing the data for the quiz(questions, options) in Azure blob storage.
When the json is stored locally adn in the same folder and I use getJSON to make the call, it works. According to this thread, Query JSON data from Azure Blob Storage with jQuery, that won't work if the content is in Azure blob storage, but when I tried to make the modifications as described in thread, I get nothing. Any help is greatly appreciated. Below, I've included my HTML, JSON and JS.
HTML:
<!DOCTYPE HTML>
<head>
<title>HTML5 - Multiple Choose Quiz Sample</title>
<link href="main.css" rel="stylesheet" type="text/css"/>
<script src="jquery.js"></script>
<script src="controller.js"></script>
<script type="text/javascript" src="https://djmblob.blob.core.windows.net/quizzes/activity.json"></script>
<!--Adjust for mobile phones-->
<meta name=viewport content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
<body>
<!--comenting out for now...tes<div id="topbar">HTML5 MCQ Quiz</div>-->
<!--comenting out for now...<div class="spacer"></div>-->
<div id="navContent">
<div id="game1"></div>
<div id="game2"></div>
</div>
</body>
JSON:
dataCallback({"quizlist":[
{
"question":"Josh Hutcherson is known for his main role in the movie series The Hunger Games, but in what other movie was he the main character?",
"option1":"The Polar Express",
"option2":"John Tucker Must Die",
"option3":"The Alamo"
},
{
"question":"Who was the villain in Othello?",
"option1":"Iago",
"option2":"His Wife",
"option3":"Cassio"
},
{
"question":"What was Will Smith’s character Mike Lowery’s middle name in the movie series Bad Boys?",
"option1":"Eugene",
"option2":"Eric",
"option3":"Brian"
},
{
"question":"At the 2001 Academy Award, what movie won both the Best Picture and Best Actor in a Leading Role award?",
"option1":"Gladiator",
"option2":"Traffic",
"option3":"Erin Brockovich"
},
{
"question":"Who was the original killer in Friday the 13th?",
"option1":"Jason's mother",
"option2":"Freddy",
"option3":"Jason"
},
{
"question":"Who played the main female role in G.I. Jane?",
"option1":"Demi Moore",
"option2":"Megan Fox",
"option3":"Lucy Lu"
},
{
"question":"In what year was Dude, Who Stole My Car? released?",
"option1":"2000",
"option2":"2005",
"option3":"2014"
},
{
"question":"What character does Michael B. Jordan play in the 2015 Fantastic 4?",
"option1":"Human Torch",
"option2":"Mister Fantastic",
"option3":"Thing"
},
{
"question":"Who played the voice of the Lorax?",
"option1":"Danny DeVito",
"option2":"Mel Gibson",
"option3":"George Clooney"
},
{
"question":"What was the character's name Tom Hanks played in the Green Mile?",
"option1":"Paul Edgecomb",
"option2":"John Coffey",
"option3":"Percy Wetmore"
}
]
})
JS:
$(document).ready(function () {
var questionNumber=0;
var questionBank=new Array();
var stage="#game1";
var stage2=new Object;
var questionLock=false;
var numberOfQuestions;
var score=0;
function dataCallback(data) {
for(i=0;i<data.quizlist.length;i++){
questionBank[i]=new Array;
questionBank[i][0]=data.quizlist[i].question;
questionBank[i][1]=data.quizlist[i].option1;
questionBank[i][2]=data.quizlist[i].option2;
questionBank[i][3]=data.quizlist[i].option3;
}
numberOfQuestions=questionBank.length;
displayQuestion();
}//gtjson
function displayQuestion(){
var rnd=Math.random()*3;
rnd=Math.ceil(rnd);
var q1;
var q2;
var q3;
if(rnd==1){q1=questionBank[questionNumber][1];q2=questionBank[questionNumber][2];q3=questionBank[questionNumber][3];}
if(rnd==2){q2=questionBank[questionNumber][1];q3=questionBank[questionNumber][2];q1=questionBank[questionNumber][3];}
if(rnd==3){q3=questionBank[questionNumber][1];q1=questionBank[questionNumber][2];q2=questionBank[questionNumber][3];}
$(stage).append('<div class="questionText">'+questionBank[questionNumber][0]+'</div><div id="1" class="option">'+q1+'</div><div id="2" class="option">'+q2+'</div><div id="3" class="option">'+q3+'</div>');
$('.option').click(function(){
if(questionLock==false){questionLock=true;
//correct answer
if(this.id==rnd){
$(stage).append('<div class="feedback1">Correct</div>');
score++;
}
//wrong answer
if(this.id!=rnd){
$(stage).append('<div class="feedback2">Incorrect</div>');
}
setTimeout(function(){changeQuestion()},500);
}})
}//display question
function changeQuestion(){
questionNumber++;
if(stage=="#game1"){stage2="#game1";stage="#game2";}
else{stage2="#game2";stage="#game1";}
if(questionNumber<numberOfQuestions){displayQuestion();}else {displayFinalSlide();}
$(stage2).animate({"right": "+=800px"},"slow", function() {$(stage2).css('right','-800px');$(stage2).empty();});
$(stage).animate({"right": "+=800px"},"slow", function() {questionLock=false;});
}//change question
function displayFinalSlide(){
$(stage).append('<div class="questionText">You have finished the quiz!<br><br>Total questions: '+numberOfQuestions+'<br>Correct answers: '+score+'<br><br>Exit</div>');
}//display final slide
});//doc ready
So I found the solution by adjusting my JS as shown below by using the ajax function in jQuery. The solution located here, http://blogs.msdn.com/b/tconte/archive/2011/08/10/accessing-windows-azure-blob-storage-using-jquery.aspx led me down the right path. I hope this helps someone else.
$.ajax({
url: 'https://djmblob.blob.core.windows.net/quizzes/activity.json',
dataType: 'jsonp',
jsonpCallback: 'dataCallback',
success: function (data) {
for(i=0;i<data.quizlist.length;i++){
questionBank[i]=new Array;
questionBank[i][0]=data.quizlist[i].question;
questionBank[i][1]=data.quizlist[i].option1;
questionBank[i][2]=data.quizlist[i].option2;
questionBank[i][3]=data.quizlist[i].option3;
}
numberOfQuestions=questionBank.length;
displayQuestion();
}//gtjson
});

Categories

Resources