Javascript to send notice to discord based on webpage last updated - javascript

I'm attempting to create a page that when it's been updated, it sends a notice to a channel in discord. I have a working page with a button that will send a notice to discord(uses webhooks and javascript). I'm stuck on executing use of document.lastModified to detect when the page was last updated so that it can execute the onclick=sendMessage(). Any/all help with this would be appreciated.
-Matt
My code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Discord Webhook Tutorial</title>
</head>
<body>
<button onclick="sendMessage()">Send</button>
</body>
<script>
mess1= document.lastModified;
math=99;
x = hidden(mess1);
if (x == true)
{
function sendMessage() {
var request = new XMLHttpRequest();
request.open("POST", "https://discordapp.com/api/webhooks/736073177125355570/yn5upyFa_7IkqwRXlO9XPzooIyMWkqM7wIXcIjqSR6SlhYD8eBCWOm7vEVl4vmNjQBxL");
request.setRequestHeader('Content-type', 'application/json');
var params = {
username: "Update Bot",
avatar_url: "",
content: "Testing bot... updating..."
}
request.send(JSON.stringify(params));
}
}
</script>
</html>

You will need to store the lastModified value somewhere to be able to compare it.
The only value that you have in the DOM is the current one.
You could do this:
const current = document.lastModified;
// Get the last known modified timestamp
const previous = localStorage.getItem('lastModified');
// Update the current modified timestamp
localStorage.setItem('lastModified', current);
// If they differ, trigger the webhook
if (current !== previous) {
doTheXHRThing();
}

Related

Call a function on Input Completion

I have a name input on 1.html.
I need to call a function where the input will be stored after completion, and when the person clicks ~next~ to go to the next page (2.html), whatever was stored appears there.
Example:
~1.html~
What's your name?
~input~ John ~input~
~2.html~
Hi, John! How can i help you?
I know i can use Session Storage to do it, but i'm not sure on how to proceed.
Here's what i have:
1.html
<p>"Whats Your Name?"</p>
<input id="your-name-input" type="text">
<a href="2.html">
<button id="next-button">Next</button>
<script>
nextButton = document.getElementById("next-button);
nextButton.addEventListener("click", () => {
var name = document.getElementbyId("your-name-input").value;
if(name !== "") {
sessionStorage.setItem("name", name);
} else {
alert("Please fill yout name")
});
</script>
And then, on 2.html i have:
<p id="user-name"></p>
What i'm trying to do, is to put inside the <p>, the following greeting:
Hi (name.value), how can i help you?
How can i call a function that loads the name value on the 2.html page when the page loads?
The below code should work. There are a few things missing in your code, not sure if you copied everything in.
In either case, the below works for me. You just need to update the link in the window.location = syntax. When you do that, it will take your stored value to the new page in the same tab, and display it using the script code in 2.html.
Code in 1.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
<title>Your name test</title>
</head>
<body>
<p>Whats Your Name?</p>
<input id="your-name-input" type="text">
<button id="next-button">Next</button>
<script>
const nextButton = document.getElementById("next-button");
const input = document.getElementById("your-name-input");
nextButton.addEventListener("click", () => {
const name = input.value;
if(name !== "") {
sessionStorage.setItem("name", name);
window.location = "<link to your 2.html file>";
} else {
alert("Please fill your name")
}
});
</script>
</body>
<footer>
</footer>
</html>
Code in 2.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
<title>See, it works</title>
</head>
<body>
<p id="user-name"></p>
<script>
const displayText = document.getElementById("user-name");
const storedValue = sessionStorage.getItem("name");
console.log(storedValue);
window.addEventListener("load", () => {
displayText.innerHTML = "Hi " + storedValue;
})
</script>
</body>
<footer>
</footer>
</html>
Original ans to original question:
You could use an addEventListener with an IF statement for your 'next' button and then the code you already have for localStorage.
Depending on what you need from your page, you could also use sessionStorage - that one doesn't save the input forever so might save, albeit limited, space on your user's computer.
I don't see the HTML for your button yet. But assuming you have it, here's an option for the rest of your code in 1.html.
Inside 1.html script tag:
nextButton = document.getElementById("yourButtonID");
nextButton.addEventListener("click", () => {
var name = document.getElementById("your-name-input").value;
if(name !== "") { // if input is not empty
localStorage.setItem("name", name); // set the value in localStorage
} else {
alert("Please fill your name")} // else, display an alert (if you like)
});

How to change an Id on another page as it loads through JavaScript

I want for the user to click a button which leads to another page. Depending on what button the user clicks, the page content should look different despite being on the same page. A simplified example is below:
Starting page html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Click Here
Click Here
<script src="script.js"></script>
</body>
</html>
second-page.html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="content-id">*CONTENT SHOULD BE LOADED HERE BASED OFF BUTTON CLICKED*</p>
<script src="script.js"></script>
</body>
</html>
script.js code:
function changeContent(n) {
document.getElementById("content-id").innerHTML = n;
}
The above code does not work. I'm guessing the browser doesn't see the content-id on the first page and fails to change anything before loading the second page. Any way to reference the right id on the right page using JavaScript (no jQuery) when the new page is loaded?
Short answer: there are several approaches, the easier that comes to mind is to use localStorage if you're dealing with same origin pages
What you need is to have user information available across multiple pages. So, unlike sessionStorage, localStorage allows to store data and save it across browser sessions:
localStorage is similar to sessionStorage, except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed.
To use it, consider adapting your javascript of first page:
function changeContent(n) {
localStorage.setItem('optionChosen', n);
}
Then retrieve it in the second page's javascript.
var opt = localStorage.getItem('optionChosen')
var content = document.querySelector('#content-id')
if (opt == null) console.log("Option null")
if (opt === 'Option One') content.innerText = "Foo"
if (opt === 'Option Two') content.innerText = "Bar"
Edited -
Added 3 working examples that can be copy and pasted.
Problem -
Display content on a new view based on the button clicked to get to that view.
Approach -
You can store the value of ID in the browser to help identify the content that should be displayed in many ways. I will show you three working examples.
Notes -
I am over complicating this a little to show you how you might make this work since I do not know the exact circumstances you are working with. You should be able to use this logic to refactor for your requirements. You will find the following 3 solutions below.
1. Using GET Params
Uses the GET params in the URL to help you track necessary changes in your view.
2. Using Session Storage
A page session lasts as long as the browser is open, and survives over page reloads and restores.
Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
Closing a tab/window ends the session and clears objects in sessionStorage.
3. Using Local Storage
The difference between localStorage and sessionStorage is the time the data persists. LocalStorage spans multiple windows and lasts beyond the current session.
The memory capacity may change by browser.
Similar to cookies, localStorage is not permanent. The data stored within it is specific to the user and their browser.
Solutions -
Working Examples - (Copy and paste any of the below solutions into an HTML file and they will work in your browser.)
Using GET Params
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
let currentURL = window.location.href.split("?")[0];
function appendParams(val) {
if (val === "a") {
window.location.assign(currentURL + "?id=a");
}
if (val === "b") {
window.location.assign(currentURL + "?id=b");
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="appendParams('a')">Click Here</button>
<button onclick="appendParams('b')">Click Here</button>
<p id="replace-id"></p>
</body>
</html>
<script type="text/javascript">
let url_str = window.location.href;
let url = new URL(url_str);
let search_params = url.searchParams;
let id = search_params.get("id");
document.getElementById("replace-id").id = id;
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("a").innerHTML = ContentOne;
}
if (id === "b") {
document.getElementById("b").innerHTML = ContentTwo;
}
</script>
Using Session Storage
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
sessionStorage.setItem("id", "default");
function addSessionStorage(val) {
sessionStorage.setItem("id", val);
updateContent();
}
function updateContent() {
let id = sessionStorage.getItem("id");
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("replace-content").innerHTML =
ContentOne;
}
if (id === "b") {
document.getElementById("replace-content").innerHTML =
ContentTwo;
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="addSessionStorage('a')">Click Here</button>
<button onclick="addSessionStorage('b')">Click Here</button>
<p id="replace-content">Default Content</p>
</body>
</html>
Using Local Storage
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
localStorage.setItem("id", "default");
function addLocalStorage(val) {
localStorage.setItem("id", val);
updateContent();
}
function updateContent() {
let id = localStorage.getItem("id");
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("replace-content").innerHTML =
ContentOne;
}
if (id === "b") {
document.getElementById("replace-content").innerHTML =
ContentTwo;
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="addLocalStorage('a')">Click Here</button>
<button onclick="addLocalStorage('b')">Click Here</button>
<p id="replace-content">Default Content</p>
</body>
</html>

JS not responding to updated txt file

Aim:
The background loop will continuously read and print the file (word.txt)
Pressing one of the buttons will overwrite the value in word.txt
This change will then be read by the background loop and printed
What happens:
The background loop continuously reads and prints the file (word.txt)
Pressing one of the buttons overwrites the value in word.txt
but.... 3. This change isn't reflected in JS until I go on to the "word.txt" file in a different browser and refresh the page. Once this is done, JS starts recognizing it.
Any ideas? Sorry the snippet doesn't work as it has php in
var instanse = false;
var state;
var mes;
var file;
console.log('update.js loaded');
function triggerUpdate(){
console.log('update.js is triggered');
updateChat();
}
//Background Loop
function updateChat(){
var file = 'word.txt';
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
console.log(allText);
}
}
}
rawFile.send(null);
setTimeout(updateChat, 1500);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Random Word Generator</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script language="javascript" src="update.js" type="text/javascript"></script>
</head>
<body onload="triggerUpdate();">
<form action="" method="post">
<input type="submit" name="word"
class="button" value="Button1" id="button1"/>
<input type="submit" name="word"
class="button" value="Button2" id="button2"/>
</form>
<?php
//This function gets called when button is pushed
function postword(){
$fp = fopen('word.txt', 'w');
fwrite($fp, $_POST['word']);
fclose($fp);
}
//When the button is pushed, the function will be called
if (isset($_POST['word'])) {
postword();
return;
}
?>
</body>
</html>
The browser is caching the initial result of the XMLHttpRequest call. The easiest workaround is to fool the cache by appending a random number as a parameter to the url. it will get ignored by the filesystem when looking for the file.
You can add any query variable you want ('v' is popular - sort of stands for version).
There are many ways to get a random number but using the Unix timestamp - Date.now()
- is an easy one that should do the trick in this case.
Change code from:
var file = 'word.txt';
To:
var file = 'word.txt?v=' + Date.now();
This which will create a call to a url like this: word.txt?v=1519211809934

Google chrome is not firing onResult event on voice

Everything is working fine in this code except the result showing part after receiving any audio.Can someone tell me why this is not logging any value in console even after i speak in the headphone.
<!DOCTYPE html>
<head></head>
<body>
<div id="msg"></div>
<div id="msg2"></div>
<script>
(function(){
var reco = new webkitSpeechRecognition();
var msgid = document.getElementById('msg');
reco.interimResults = true;
reco.addEventListener('start',function(){
msgid.innerHTML = 'Listening...';
});
reco.addEventListener('audiostart',function(){
msgid.innerHTML = 'Recording...';
});
reco.start();
reco.onresult = function(e){
console.log(e);
}
})()
</script>
</body>
However, SpeechRecognition() is a constructor which is not supported by most of the browers, if you are running it in firefox, it won't help. Try this code in chrome. Later on in console -> Search for result -> Expand the result tab -> Search something called transcript. There it is, your recorded text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<button class="talk">Talk</button>
<h3 class="content"></h3>
<script>
const btn = document.querySelector(".talk");
const content = document.querySelector(".content");
const SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition;
const myRecognition = new SpeechRecognition();
myRecognition.onstart = function() {
console.log("voice is activated, you may now speak");
};
myRecognition.onresult = function() {
console.log(event);
};
//adding eventListener
btn.addEventListener("click", () => {
myRecognition.start();
});
</script>
</body>
</html>
Internet connection is required for working with speech recognition since the recorded speech must be fed through internet connection to a web service for processing.
https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API

Unable to call a Javascript class from HTML

Please have a look at the below code
TTSScript.js
function TTS()
{
var msg = new SpeechSynthesisUtterance("yohan");
var voices = window.speechSynthesis.getVoices();
this.speakText = function()
{
window.speechSynthesis.speak(msg);
}
}
index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/scripts/TTSScript.js"></script>
<script>
function speak()
{
var msg = new SpeechSynthesisUtterance('Hello World');
window.speechSynthesis.speak(msg);
}
function speak2()
{
var TTS = new TTS();
TTS.speakText();
}
</script>
</head>
<body>
<div><button onclick="speak2()">Click me</button></div>
</body>
</html>
Unfortunatly when I click on the button in the html page, what I get is an error. It is below.
Uncaught TypeError: undefined is not a function (13:42:13:817 | error, javascript)
at speak2 (public_html/index.html:23:26)
at onclick (public_html/index.html:31:126)
I am not much familiar with JavaScript, can you please let me know why I am getting this error and how to fix it?
After declaring a function, its name becomes a (locally) preserved word. It means that creating a variable with the same name might cause some problems.
I took your code and changed
var TTS = new TTS();
TTS.speakText();
Into
var tts = new TTS();
tts.speakText();
And the error disappeared.
I solved your problem.. :
don't use all capital names as variables
var tts = new TTS();
tts.speakText();
correct speak call is in the fiddle
http://jsfiddle.net/bpprwfxa/4/
var msg = new SpeechSynthesisUtterance('Yohan');
window.speechSynthesis.speak(msg);

Categories