Getting error TypeError: document.getElementById(...) is null as function is called for the second time - typeerror

I am using this code
<script type="text/javascript">
function loadXMLDoc()
{
var testValue = document.getElementById("test").value;
document.getElementById("test").value = ++testValue;
var testValue2 = document.getElementById("test").value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("3");
document.getElementById("loading").style.display = "none";
alert("4");
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
alert("1");
document.getElementById("loading").style.display = "block";
alert("2");
xmlhttp.open("GET","catalog/view/theme/default/template/information/latest_newsroom.php?q="+testValue2,true);
xmlhttp.send();
}
</script>
<form name="testForm" method="post" action="">
<input type="text" name="test" id="test" value="1" />
<input type="button" name="testButton" value="More" onclick="loadXMLDoc()" />
</form>
and it gives the error :
TypeError: document.getElementById(...) is null
as my function runs for the second time.

The error is corect.
You have set var testValue = document.getElementById("test").value;
so this document.getElementById("test").value = ++testValue;
should be testValue.value = ++testValue; since testValue is now a variable.
Below is what i have sugested in the comment:
<script type="text/javascript">
function loadXMLDoc()
{
var testValue = document.getElementById("test").value;
document.getElementById("test").value = ++testValue;
var testValue2 = document.getElementById("test").value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("3");
document.getElementById("loading").style.display = "none";
alert("4");
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
else
{
document.getElementById("loading").style.display = "block";
}
}
alert("1");
alert("2");
xmlhttp.open("GET","catalog/view/theme/default/template/information/latest_newsroom.php?q="+testValue2,true);
xmlhttp.send();
}
</script>
<form name="testForm" method="post" action="">
<input type="text" name="test" id="test" value="1" />
<input type="button" name="testButton" value="More" onclick="loadXMLDoc()" />
</form>

Related

How to modify and convert Google app UI into HTML

I try to convert this simple google apps script code below to HTML services code. The code below is written with the deprecated google apps script UI services! Could anyone please help me with HTML services example code in this usecase?
I'm not really sure how to approach it as I haven't been coding for too long.
A little bit of help would be very much appreciated.
Thanks!!
Mireia
function() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
app.setHeight(400);
var scriptProps = PropertiesService.getScriptProperties();
var label1 = app.createLabel('XERO Settings').setStyleAttribute('font-weight', 'bold').setStyleAttribute('padding', '5px').setId('label1');
var panel1 = app.createVerticalPanel().setId('panel1');
var grid = app.createGrid(7, 2);
var absPanel = app.createAbsolutePanel();
var handler = app.createServerHandler('saveSettings');
var clientHandler1 = app.createClientHandler();
var clientHandler2 = app.createClientHandler();
var clientHandler3 = app.createClientHandler();
var btnSave = app.createButton('Save Settings', handler);
var lblAppType = app.createLabel('Application Type: ');
var appTypes = {Private:0, Public:1, Partner:2};
var listAppType = app.createListBox().setName('appType').addItem('Private').addItem('Public').addItem('Partner').addChangeHandler(clientHandler1).
addChangeHandler(clientHandler2).addChangeHandler(clientHandler3).setSelectedIndex(appTypes[(scriptProps.getProperty('appType') != null ? scriptProps.getProperty('appType'): 'Private')]);
handler.addCallbackElement(listAppType);
var lblAppName = app.createLabel('Application Name: ');
var txtAppName = app.createTextBox().setName('userAgent').setWidth("350")
.setValue((scriptProps.getProperty('userAgent') != null ? scriptProps.getProperty('userAgent'): ""));
handler.addCallbackElement(txtAppName);
var lblConsumerKey = app.createLabel('Consumer Key: ');
var txtConsumerKey = app.createTextBox().setName('consumerKey').setWidth("350")
.setValue((scriptProps.getProperty('consumerKey') != null ? scriptProps.getProperty('consumerKey'): ""));
handler.addCallbackElement(txtConsumerKey);
var lblConsumerSecret = app.createLabel('Consumer Secret: ');
var txtConsumerSecret = app.createTextBox().setName('consumerSecret').setWidth("350")
.setValue((scriptProps.getProperty('consumerSecret') != null ? scriptProps.getProperty('consumerSecret'): ""));
handler.addCallbackElement(txtConsumerSecret);
var lblcallBack = app.createLabel('Callback URL:');
var txtcallBack = app.createTextBox().setName('callBack').setWidth("350")
.setValue((scriptProps.getProperty('callbackURL') != null ? scriptProps.getProperty('callbackURL'): ""));
handler.addCallbackElement(txtcallBack);
var lblRSA = app.createLabel('RSA Private Key:');
var txtareaRSA = app.createTextArea().setName('RSA').setWidth("350").setHeight("150")
.setValue((scriptProps.getProperty('rsaKey') != null ? scriptProps.getProperty('rsaKey'): ""));
if (scriptProps.getProperty('appType') == "Private" || scriptProps.getProperty('appType') == null)
txtcallBack.setEnabled(false);
else if (scriptProps.getProperty('appType') == "Public")
txtareaRSA.setEnabled(false);
handler.addCallbackElement(txtareaRSA);
clientHandler1.validateMatches(listAppType, 'Private').forTargets(txtcallBack).setEnabled(false).forTargets(txtareaRSA).setEnabled(true);
clientHandler2.validateMatches(listAppType, 'Public').forTargets(txtcallBack).setEnabled(true).forTargets(txtareaRSA).setEnabled(false);
clientHandler3.validateMatches(listAppType, 'Partner').forTargets(txtcallBack).setEnabled(true).forTargets(txtareaRSA).setEnabled(true);
grid.setBorderWidth(0);
grid.setWidget(0, 0, lblAppType);
grid.setWidget(0, 1, listAppType);
grid.setWidget(1, 0, lblAppName);
grid.setWidget(1, 1, txtAppName);
grid.setWidget(2, 0, lblConsumerKey);
grid.setWidget(2, 1, txtConsumerKey);
grid.setWidget(3, 0, lblConsumerSecret);
grid.setWidget(3, 1, txtConsumerSecret);
grid.setWidget(4, 0, lblcallBack);
grid.setWidget(4, 1, txtcallBack);
grid.setWidget(5, 0, lblRSA);
grid.setWidget(5, 1, txtareaRSA);
grid.setWidget(6, 1, btnSave);
panel1.add(grid).setStyleAttributes(subPanelCSS);
app.add(label1);
app.add(panel1);
ss.show(app);
}
Description
Unfortunately there is no converter. Your dialog is relatively simple and I think I have captured everything of interest. I expect you to handle the property services.
In the dialog I changed the appType from Public to Private to show that the changed values are sent to the server for property service as shown in the execution log.
I inadvertently put include in Code.gs because I normally put CSS in one file, HTML another and js in a third. I didn't do that in this instance.
HTML_Test
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
#label1 { font-weight: bold; }
.textBox { width: 350px; }
.table { display: table; }
.table-row { display: table-row; }
.table-cell { display: table-cell; }
</style>
</head>
<body>
<p id="label1">XERO Settings</p>
<div class="panel1">
<div class="table">
<div class="table-row">
<div class="table-cell">Application Type:</div>
<div class="table-cell">
<select class="textBox" id="appType" onchange="appTypeOnChange()">
<option>Private</option>
<option>Public</option>
<option>Partner</option>
</select>
</div>
</div>
<div class="table-row">
<div class="table-cell">Application Name:</div>
<div class="table-cell">
<input class="textBox" id="userAgent" value=<?= userAgent?>>
</div>
</div>
<div class="table-row">
<div class="table-cell">Consumer Key:</div>
<div class="table-cell">
<input class="textBox" id="consumerKey" value=<?= consumerKey ?>>
</div>
</div>
<div class="table-row">
<div class="table-cell">Consumer Secret:</div>
<div class="table-cell">
<input class="textBox" id="consumerSecret" value=<?= consumerSecret ?>>
</div>
</div>
<div class="table-row">
<div class="table-cell">Callback URL:</div>
<div class="table-cell">
<input class="textBox" id="callBack" value=<?= callBack ?>>
</div>
</div>
<div class="table-row">
<div class="table-cell">RSA Private Key:</div>
<div class="table-cell">
<input class="textBox" id="rsaKey" value=<?= rsaKey ?>>
</div>
</div>
</div>
</div>
<input class="btnSave" type="button" value="Save Settings" onclick="saveSettings()">
<script>
function appTypeOnChange() {
let value = document.getElementById("appType").value;
if( value == "Private" ) {
document.getElementById("callBack").disabled = true;
document.getElementById("rsaKey").disabled = false;
}
else if( appType == "Public" ) {
document.getElementById("callBack").disabled = false;
document.getElementById("rsaKey").disabled = true;
}
else {
document.getElementById("callBack").disabled = false;
document.getElementById("rsaKey").disabled = false;
}
}
function saveSettings() {
let props = {};
props.appType = document.getElementById("appType").value;
props.userAgent = document.getElementById("userAgent").value;
props.consumerKey = document.getElementById("consumerKey").value;
props.consumerSecret = document.getElementById("consumerSecret").value;
props.callBack = document.getElementById("callBack").value;
props.rsaKey = document.getElementById("rsaKey").value;
props = JSON.stringify(props);
google.script.run.setProperties(props);
}
(function () {
let appType = <?= appType ?>;
document.getElementById("appType").value=appType;
if( appType == "Private" ) {
document.getElementById("callBack").disabled = true;
}
else if( appType == "Public" ) {
document.getElementById("rsaKey").disabled = true;
}
}());
</script>
</body>
</html>
Dialog
Code.gs
function showTest() {
try {
let html = HtmlService.createTemplateFromFile('HTML_Test');
html.appType = "Public";
html.userAgent = "John Smith";
html.consumerKey = "12345678";
html.consumerSecret = "My Secret";
html.callBack = "www.goggle.com";
html.rsaKey = "abcdefg";
html = html.evaluate();
SpreadsheetApp.getUi().showModalDialog(html,"Show Test");
}
catch(err) {
SpreadsheetApp.getUi().alert(err);
}
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
};
function setProperties(props) {
Logger.log(props);
}
Execution log
Head setProperties Unknown May 11, 2022, 8:27:15 AM 0.57 s
Completed
Cloud logs
May 11, 2022, 8:27:16 AM Info {"appType":"Private","userAgent":"John Smith","consumerKey":"12345678","consumerSecret":"My Secret","callBack":"www.goggle.com","rsaKey":"abcdefg"}
Reference
HTML Service Templated HTML

how do you loop through checkboxes using puppeteer?

I have a list of checkboxes , every time puppeteer run the test I need to :
if a box is already selected then
move to next box and select it , and if the next is selected move to the next checkbox and so on
if(await page.$eval(firstcheckbox, check=>check.checked =true)) { //check if the box is selected
await page.waitForSelector(do something, ele=>elem.click())//if the checkbox is already selected , move to the second row and select a undecked box
}else if{
await page.$eval(firstcheckbox, check=>check.checked =false)){ //if the checkbox is not ticked
await page.$eval(clickcheckbox, elem=>elem.click);//tick the checkbox
You can use all the testing and changing inside one page.evaluate():
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({ headless: false, defaultViewport: null });
const html = `
<!doctype html>
<html>
<head><meta charset='UTF-8'><title>Test</title></head>
<body>
<input type="checkbox" id="checkbox1"><label for="checkbox1">checkbox1</label><br>
<input type="checkbox" id="checkbox2" checked><label for="checkbox2">checkbox2</label><br>
<input type="checkbox" id="checkbox3" checked><label for="checkbox3">checkbox3</label><br>
<input type="checkbox" id="checkbox4"><label for="checkbox4">checkbox4</label><br>
</body>
</html>`;
try {
const [page] = await browser.pages();
await page.goto(`data:text/html,${html}`);
await page.evaluate(() => {
for (const checkbox of document.querySelectorAll('input')) {
if (!checkbox.checked) checkbox.click();
}
});
console.log('Done.');
} catch (err) { console.error(err); }
Or, if you need a loop over element handles, you can try this:
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({ headless: false, defaultViewport: null });
const html = `
<!doctype html>
<html>
<head><meta charset='UTF-8'><title>Test</title></head>
<body>
<input type="checkbox" id="checkbox1"><label for="checkbox1">checkbox1</label><br>
<input type="checkbox" id="checkbox2" checked><label for="checkbox2">checkbox2</label><br>
<input type="checkbox" id="checkbox3" checked><label for="checkbox3">checkbox3</label><br>
<input type="checkbox" id="checkbox4"><label for="checkbox4">checkbox4</label><br>
</body>
</html>`;
try {
const [page] = await browser.pages();
await page.goto(`data:text/html,${html}`);
for (const checkbox of await page.$$('input')) {
if (!await checkbox.evaluate(elem => elem.checked)) {
await checkbox.click();
}
}
console.log('Done.');
} catch (err) { console.error(err); }

How can I make my WebRTC is working properly

Now I am building a video call site with WebRTC. But it recognize camera and ask to allow camera.
When I allow camera it shows nothing.
I will write down my code here.
<body onload="init()">
<div class="row">
<div class="col-8">
<form action="#">
<h5>Current Room ID: <span id="curr_room_id"></span><br/></h5>
<input id="new_room_id" name="room" type="text" placeholder="Enter a room id to connect..." style="padding: 5px"/>
<input type="submit" id="connect" value="Connect" />
</form>
<input id="call" type="submit" value="Call" disabled="true"/>
<input id="end" type="submit" value="End Call"disabled="true"/>
</div>
<div class="col-4" id="google_translate_element"></div>
</div>
<h1>local</h1>
<video id="local_video" width="400px" style="border: 1px solid black;"></video>
<h1>remote</h1>
<video id="remote_video" width="400px" style="border: 1px solid black;"></video>
<script src="/socket.io/socket.io.js"></script>
<script src="../scripts/video-client.js"></script>
<script src="../scripts/video-room.js"></script>
<script>
function init() {
console.log("document loaded");
call.removeAttribute("disabled");
call.addEventListener("click", function(){
createPeerConnection();
call.setAttribute("disabled", true);
end.removeAttribute("disabled");
});
end.addEventListener("click", function() {
// change rooms
end.setAttribute("disabled", true);
call.removeAttribute("disabled");
});
}
</script>
</body>
I think it is because of not showing video stream to webview. But i didn't find nothing. Please tell me.
And here is video-client.js
console.log("loaded");
var socket = io();
var local = document.getElementById("local_video");
var remote = document.getElementById("remote_video");
var call = document.getElementById("call");
var end = document.getElementById("end");
var room_id = document.getElementById("curr_room_id");
var localStream = null, remoteStream = null;
var config = {'iceServers' : [{'url' : 'stun:stun.l.google.com:19302'}]};
var pc;
/////////////////////////////////
function createPeerConnection() {
try {
pc = new RTCPeerConnection(config);
pc.onicecandidate = handleIceCandidate;
pc.onaddstream = handleRemoteStreamAdded;
pc.onremovestream = handleRemoteStreamRemoved;
pc.onnegotiationneeded = handleNegotiationNeeded;
getUserMedia(displayLocalVideo);
pc.addStream(localStream);
console.log("Created RTCPeerConnection");
} catch (e) {
console.log("Failed to create PeerConnection: " + e.message);
return;
}
}
function handleIceCandidate(event) {
console.log("handleIceCandidate event: " + event);
if(event.candidate) {
sendMessage(JSON.stringify({'candidate': evt.candidate}));
} else {
consolel.log("End of ice candidates");
}
}
function handleRemoteStreamAdded(event) {
console.log("Remote stream added");
displayRemoteVideo(event.stream);
call.setAttribute("disabled", true);
end.removeAttribute("disabled");
}
function handleRemoteStreamRemoved(event) {
console.log("Remote stream removed: " + event);
end.setAttribute("disabled", true);
call.removeAttribute("disabled");
local.src = "";
remote.src = "";
}
function handleNegotiationNeeded() {
pc.createOffer(localDescCreated, logError);
}
function localDescCreated(desc) {
pc.setLocalDescription(desc, function() {
sendMessage(JSON.stringify({'sdp': pc.localDescription}));
}, logError);
}
call.onclick(function(){
createPeerConnection();
});
/////////////////////////////////
function getUserMedia(callback) {
navigator.mediaDevices.getUserMedia({video: true, audio: false}).then(
function(stream) {
callback(stream);
return stream;
}).catch(logError);
}
function displayLocalVideo(stream) {
localStream = stream;
local.src = window.URL.createObjectURL(stream);
local.play();
}
function displayRemoteVideo(stream) {
remoteStream = stream;
remote.src = window.URL.createObjectURL(stream);
remote.play();
}
function logError(error) {
console.log(error);
}
function sendMessage(message) {
socket.emit("message", message);
}
/////// receiving stream //////////
socket.on("message", function(evt){
if(!pc)
createPeerConnection();
var message = JSON.parse(evt.data);
if(message.sdp) {
pc.setRemoteDescription(new RTCSessionDescription(), function() {
if(pc.remoteDescription.type == 'offer')
pc.createAnswer(localDescCreated, logError);
}, logError);
} else {
pc.addIceCandidate(new RTCIceCandidate(message.candidate));
}
});
I think call.onclick() has to work properly for video streaming but it does not also.
You are not seeing your video because you are not using the stream that getUserMedia returns. You need to attach that stream to the video.

How to disable Inspect Element and f12 click?

I have a PDF which is open in new Window through Iframe, but when I disabled the f12 and inspect Element then it is not working on that PDF, it's working outside of PDF.
<body>
<div id="divPDFView" style="margin: auto;text-align: center;">
</div>
<div style="display:none;" id="divDocument">
#if (Model.MyAccountList.Count > 0)
{
foreach (var items in Model.MyAccountList)
{
<a href="#" onclick="myPdf(this)" id="#items.PdfName">
<div class="sm-video">
///There have some work
</div>
}
}
</body>
<script>
function myPdf(e) {
var filen = e.id;
debugger;
window.open('#Url.Action("pdfshow", "MyAccount")?pdfname=' + filen);
}
</script>
///Here i show PDF From View Which is pdfshow
<body>
<div>
#Html.Raw(TempData["Embed"])
</div>
</body>
This is JavaScript code which I use to disable the F12 and Inspect Element but this is work outside of PDF.
<script>
$(document).ready(function () {
debugger
document.onmousedown = disableclick;
status = "Right Click Disabled";
function disableclick(event) {
if (event.button == 2) {
alert(status);
return false;
}
}
});
</script>
<script type='text/javascript'>
$(document).keydown(function (event) {
debugger
if (event.keyCode == 123) {
return false;
}
else if (event.ctrlKey && event.shiftKey && event.keyCode == 73) {
return false; //Prevent from ctrl+shift+i
}
});
</script>
This is the controller code where PDF is created using Iframe
public ActionResult pdfshow(string pdfname = null)
{
string pdffile ="<iframe src='/Content/TutorialImage/TutorialPdf/" +
pdfname + "#toolbar=0' width='800px' height='600px'
id='myframe' oncontextmenu='return false;' >
</iframe>";
TempData["Embed"] = pdffile;
return View(TempData["Embed"]);
}

xmlhttp not working

I'm not sure what I am doing wrong. I placed this in the body, next to the div myDiv and it seems not to run, so I don't know what I am doing wrong.
<script type="text/javascript" language="javascript">
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://www.example.com/test.php",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
</script>
<div id="myDiv"></div>
The script runs before the div "myDiv" is rendered. Swap them over...
<div id="myDiv"></div>
<script type="text/javascript" language="javascript">
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://www.example.com/test.php",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;