Document Variable - javascript

I'm working on a website that plays a text to speech message,
but I want to be able to change the message with a Google document.
My question:
is it possible to make a js variable with the text in a Google Docs document?
This is my code so far:
const message = '' // Try edit me
// Update header text
document.querySelector('#header').innerHTML = message
// Log to console
console.log(message)
//message
var inter = message
//my scripts
if (inter.length===0){
location.reload();
} else{
var audio = new Audio('notif.mp3');
audio.play();
var msg = new SpeechSynthesisUtterance();
msg.text = inter;
window.speechSynthesis.speak(msg);
setTimeout(function() {
location.reload();
}, 30000);
}

Related

Chrome Extension Popup Resets On Closing

I'm trying to figure out how to make a play/pause functionality for my chrome extension. I've figured it out and it works however, for usability I now am trying to get the popup window to:
Keep the checkbox checked if it was before closing the popup.
Keep the content that popup.js wrote into a span tag before closing the popup.
My popup.html is:
<script src="popup.js"></script>
<div class="container">
<div class="checkbox">
<p>Check the box to pause the extension</p>
<input type="checkbox" id="switcher" name="switcher">
<p><span id="extensionStatus"></span></p>
</div>
<a id="submit" href="#">Save</a>
</div>
And my popup.js is:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('submit');
link.addEventListener('click', function() {
var status;
var switcher = document.getElementById('switcher');
var updateStatus = document.getElementById("extensionStatus");
if(switcher.checked == true) {
status = "paused";
} else {
status = "play";
}
chrome.storage.sync.set({'status': status});
chrome.storage.sync.get('status', function (result) {
status = result.status;
updateStatus.innerHTML = "Current Status: " + status;
if(status == "paused") {
switcher.checked = true;
}
});
});
});
I set have to set the value in storage as I also use the value to do other code on content-script file.
Basically where the line that writes the innerHTML and then the line that sets the checkbox to checked run fine when the popup is open and then as soon as you close the popup and reopen obviously the session resets.
I know it needs something like this in the popup.js instead but I am not quite sure what to put in the function in the background.js as I can't/don't know how to access the popup DOM from background.js:
var backgroundPage = chrome.runtime.getBackgroundPage();
backgroundPage.savePopup();
I don't know how extension storage works but here's a demo which works with local storage. Maybe it can help you with the extension.
Demo
document.addEventListener('DOMContentLoaded', function() {
if (localStorage.getItem('status') == 'paused') {
switcher.checked = true;
}
var link = document.getElementById('submit');
link.addEventListener('click', function() {
var status;
var switcher = document.getElementById('switcher');
var updateStatus = document.getElementById("extensionStatus");
console.log('staus:', localStorage.getItem('status'));
if (switcher.checked == true) {
status = "paused";
} else {
status = "play";
}
localStorage.setItem('status', status);
});
});

How to resolve the error of document not attached to a Window?

I am building a chrome extension which will get all the opened tabs and convert them to PNG file and download on the system.
What i have done till now
My code gets the URLs of all opened tabs and then gets the HTML DOM of each tab by using a for loop. Not i am using html2canvas to convert the html to png format, but i am getting the following error
Uncaught (in promise) Error: Document is not attached to a Window
at html2canvas.min.js:20
at html2canvas.min.js:20
at Object.next (html2canvas.min.js:20)
at html2canvas.min.js:20
at new Promise (<anonymous>)
at a (html2canvas.min.js:20)
at Vs (html2canvas.min.js:20)
at html2canvas.min.js:20
at getAllOpenWindows (popup.js:38)
My popup.js code is as follows:
// script for popup.html
window.onload = () => {
let btn = document.querySelector("#btnDL");
btn.innerHTML = "Download";
function display(){
// alert('Click button is pressed')
}
btn.addEventListener('click', display);
}
chrome.windows.getAll({populate:true}, getAllOpenWindows);
function getAllOpenWindows(winData) {
var tabs = [];
for (var i in winData) {
if (winData[i].focused === true) {
var winTabs = winData[i].tabs;
var totTabs = winTabs.length;
console.log("Number of opened tabs: "+ totTabs);
for (var j=0; j<totTabs;j++) {
tabs.push(winTabs[j].url);
tab_html_string = get_html_string(winTabs[j].url)
// get the HTML document of each tab
tab_document = get_html_document(tab_html_string)
console.log('======================')
console.log(tab_document)
html2canvas(tab_document.body, {
onrendered: function(canvas) {
var img = canvas.toDataURL("image/png")
chrome.windows.open(img);
}
});
console.log('======================')
}
}
}
console.log(tabs);
}
function get_html_document(tab_html_string){
/**
* Convert a template string into HTML DOM nodes
*/
var parser = new DOMParser();
var doc = parser.parseFromString(tab_html_string, 'text/html');
return doc;
}
function get_html_string(URL_string){
let xhr = new XMLHttpRequest();
xhr.open('GET', URL_string, false);
try {
xhr.send();
if (xhr.status != 200) {
alert(`Error ${xhr.status}: ${xhr.statusText}`);
} else {
return xhr.response
}
} catch(err) {
// instead of onerror
alert("Request failed");
}
}
In the below image you can see the opened 6 tabs in chrome with output of each tabs in the console as document reference, but the error above is irritating me. Please help me out.
output image

How to add a page refresh feature after a TTS message is read

I am trying to add a page refresh to my application after my TTS has finished talking. It should be simple enough, I just don't know TTS that well. Right now I have a Keyup that starts the sequence of TTS talking, then another Keyup that refreshes the page. But I want the refresh to occur directly after the speech finishes too.
I have tried this:
window.speechSynthesis.speak(msg);
window.location.reload();
Which obviously just reloads as the text starts talking. I have also thought about doing something like this:
window.speechSynthesis.speak(msg).window.location.reload();
But that does not seem right. I am sure it's probably close to that. Note:Below is not my complete code due to confidentiality.
var voice = speechSynthesis.getVoices();
speechSynthesis.getVoices().forEach(function(voice) {
console.log(voice.name, voice.default ? voice.default
:
'');
});
msg.pitch = 1.1;
msg.volume = 1;
msg.rate = 0.65;
msg.voice = voices[5];
msg.lang = 'en-US';
window.speechSynthesis.speak(msg);
window.location.reload();
document.addEventListener('keyup', function(e) {
if (e.keyCode == 82)
window.location.reload();
})
I just want to reload AFTER the message is spoken
You can attach a function to the onend event of your message that is spoken.
Here is a bare bones example that plays a message, and then reloads a page.
var msg = new SpeechSynthesisUtterance();
msg.text = "Hello there";
msg.onend = function(what) { console.log('event details',what); window.location.reload(); }
window.speechSynthesis.speak(msg);
Try this code to page refresh
location.reload();
or
location.reload(true);
or
window.location.reload();
or
window.location.reload(true);
or
window.location.href = window.location.href;
or
setTimeout(function(){ window.location.reload(); }, 2000);

using conditional from of chrome.storage.local.get is looping not working

I am new to chrome extension making.I was trying to store data in local storage and retrive from it. But as I put retrieve in content script it runs that before data is saved in local storage. So I was trying to make chrome.storage.local.get as a conditional. To check either it works or not I have added alert. After getting into get section it generates the alert continuously. It does not go next line.I tried both quoted undefined and nonquoted undefined.
Here is my content_script.js code:
var message;
function bodyHandler(e){
if (e.type == 'mousemove'){
chrome.storage.local.get('word', function(data) {
alert("from get");
if(typeof data.word !== undefined){
message = chrome.storage.local.get('word');
alert("from if");
}
else{
alert("from else");
message ="Hello!";
}
})
var paragraph = document.getElementsByTagName('p');
for(var i=0; i < paragraph.length; i++){
//alert('hello.');
paragraph[i].innerHTML = message;
}
}
}
document.body.addEventListener('mousemove', bodyHandler, false);
Here is my popup.js:
var evnt = document.getElementById("clicked");
function wordGetter(){
var txt= document.getElementById("wordinput").value;
chrome.storage.local.set({'word': txt});
}
evnt.addEventListener('click', wordGetter);
I cannot understand why alert("from get") is running continuously.

Notify user for video chat

I'm trying to place OpenTok video calls within my website. How do I notify a particular user for video chat?
var apiKey = "447302";
var sessionId = "1_MX40NDczMDE5Mn5";
var token = "T1==cGFydG5lcl9pZD00NDczMDE5MiZzZGtfdmVyc2l";
// Initialize session, set up event listeners, and connect
var session = TB.initSession(sessionId);
session.addEventListener('sessionConnected', sessionConnectedHandler);
session.connect(apiKey, token);
function sessionConnectedHandler(event) {
var publisher = TB.initPublisher(apiKey, 'myPublisherDiv');
session.publish(publisher);
}
session.on("streamCreated", function(e) {
for (var i = 0; i < e.streams.length; i++) {
var div = document.createElement('div');
div.setAttribute('id', 'stream' + e.streams[i].streamId);
document.getElementById('chatDiv').appendChild(div);
session.subscribe(e.streams[i], e.streams[i].streamId);
}
});
OpenTok's API does not provide any notification logic. You can notify users by playing a sound or sending alert messages.
When a new person joins your session, you will get a connectionCreated event. You can throw a notification on your connectionCreated handler.

Categories

Resources