textarea javascript debug result to innerHTML paragraph "undefined" - javascript

I am doing a code editor, almost everything is working, I type the text in the texarea and press a button to load a function, and the result of the code appears on the web browser console, I am trying to do like "document.getElementById('output').innerhtml = window.eval(txtarea.value);"
But it does not seem to work.
function DebugInp(){
var txtarea = document.getElementById('input');
document.getElementById('output').innerHTML = window.eval(txtarea.value);//output = paragraph in html.
};
/**
*My problem is that the innerHTML is showing undefined, but when I'm getting to console,
*it appears the result.
*I'm thinking of maybe getting all of the outputs of the console, but IDK how to do it
*Kind of like: document.getElementById('output').innerHTML = console.logs?
*I am still searching but any help would be nice.
*/
thanks in advance!
PS: I am better at frontend dev, trying to understand more of backend so don't hate 🙂 please.

What you're doing is very unsafe and there are many better ways to go about it. But nevertheless, you need to constrain the context of your input code. Simply evaluating the whole code won't give you the console logs. You need to expose an API for the code to send output to.
Minimal example:
var txtarea = document.getElementById('input');
document.getElementById('output').innerHTML = window.eval(`
const console = {
log(...args) {
document.getElementById('output').innerText += '\n' + args.join(' ');
}
};
${txtarea.value}
`);

OH!!! i did it guys!
Just create a new standard function for console.log so it stores every logs i found the answer right here:
https://stackoverflow.com/a/19846113/16260964
console.stdlog = console.log.bind(console);
console.logs = [];
console.log = function(){
console.logs.push(Array.from(arguments));
console.stdlog.apply(console, arguments);
}
var txtarea = document.getElementById('input');
window.eval(txtarea.value);
document.getElementById('output').innerHTML = console.logs;
GG! Have an great day everyone!🎊🎉🥳

Related

How to call a function with an event handler if the function requires the event to compile

I am currently working on a project where I need to call a script function on an event. This function is called when text is pasted into a textarea. The function copies the pasted text into an array and iterates through the array looking for the code value of Unicode right apostrophe (8217). It then replaces any found right apostrophe's with a single quote. The function works as expected. However I am running this function on 8 different pages and want to clean my code up. I placed the script into a js file that is called on every page in the project so if any more cases it is needed are found it will be easy to implement.
The function is being called with:
<script>
var instructions = document.getElementById("specialInstructions");
instructions.addEventListener("paste", pasteToPlainText);
</script>
The function in the js file is:
function pasteToPlainText(event){
var plainText;
var replaceList;
replaceList = new Array();
//converts the pasted text to plain text
if (event.clipboardData && event.clipboardData.getData){
plainText = event.currentTarget.clipboardData.getData('text/plain');
}else if (window.clipboardData){
plainText = event.currentTarget.clipboardData.getData('text/plain');
}
for (var index = 0; index < plainText.length; index++){
var rightApostropheCheck = plainText.charCodeAt(index);
//Unicode for right apostrophe is 8217 (Used in outlook email)
//Without this conversion a right apostrophe is put on screen.
// The note is unable to save with a right apostrophe
if (rightApostropheCheck == 8217){
// replaces a right apostrophe with a single quote (apostrophe)
replaceList.push("'");
}else{
// pushes all other text to the list that is printed to screen
replaceList.push(plainText[index]);
}
}
event.preventDefault();
if (event.clipboardData) {
content = replaceList.join("");
document.execCommand('insertText', false, content);
}else if (window.clipboardData) {
content = replaceList.join("");
document.selection.createRange().pasteHTML(content);
}
}
I get the error: Uncaught TypeError: Cannot read properties of undefined (reading 'clipboardData')
On the first if statement.
Any help or advice will be greatly appreciated. Thank you.
Update:
I found a solution. making the event listener with a bind statement makes sure the function is not called on load. That was the problem as the page loaded the function was called without any information. so it had undefined errors and null errors. The correct way to call the function is as follows.
<script>
var terms = document.getElementById("Terms");
terms.addEventListener("paste", pasteToPlainText.bind(terms));
</script>

Cannot get ExecuteScriptAsync() to work as expected

I'm trying to set a HTML input to read-only using ExecuteScriptAsync. I can make it work, but it's not an ideal scenario, so I'm wondering if anyone knows why it doesn't work the way I would expect it to.
I'm using Cef3, version 63.
I tried to see if it's a timing issue and doesn't appear to be.
I tried invalidating the view of the browser but that doesn't seem to help.
The code I currently have, which works:
public void SetReadOnly()
{
var script = #"
(function(){
var labelTags = document.getElementsByTagName('label');
var searchingText = 'Notification Initiator';
var found;
for (var i=0; i<labelTags.length; i++)
{
if(labelTags[i].textContent == searchingText)
{
found = labelTags[i]
break;
}
}
if(found)
{
found.innerHTML='Notification Initiator (Automatic)';
var input;
input = found.nextElementSibling;
if(input)
{
input.setAttribute('readonly', 'readonly');
}
}})()
";
_viewer.Browser.ExecuteScriptAsync(script);
_viewer.Browser.ExecuteScriptAsync(script);
}
now, if I remove
found.innerHTML='Notification Initiator (Automatic)';
the input is no longer shown as read-only. The HTML source of the loaded webpage does show it as read-only, but it seems like the frame doesn't get re-rendered once that property is set.
Another issue is that I'm executing the script twice. If I run it only once I don't get the desired result. I'm thinking this could be a problem with V8 Context that is required for the script to run. Apparently running the script will create the context, so that could be the reason why running it twice works.
I have been trying to figure this out for hours, haven't found anything that would explain this weird behaviour. Does anyone have a clue?
Thanks!

Retrieving the error elements in Pega 8.1 Tree Navigation Flow

I am currently working on Pega. I am basically new in it. Pega version which I am working is 8.1.
Actually in the flow while submitting a form whenever there are validation errors in the required fields there an alert pops up. But as far as UI and UX the window needs to scroll with a subtle animation to the error fields, this I can do perfectly for any HTML page using jquery, but as I am new to Pega, I am facing a problem to get the error fields.
What I find, the error fields are appending on the relevant fields whenever there are validations, but catching those elements are going undefined.
I am sharing the simple code which I have written:
var validateScroll = function(){
var getErrors = function(){
this.parent = "";
}
getErrors.prototype.getErrorfn = function(node){
this.parent = $(node);
var errorLabels = this.parent.find('.dynamic-icon-error');
console.log(errorLabels.attr('class'))
}
var a = new getErrors();
var scrollfn = function(){
var forms = $(document).find('form')[0];
var _FORM = $(forms);
_FORM.on('submit',a.getErrorfn(_FORM));
}
return{
init:function(){
scrollfn();
}
}
}();
$(document).ready(function(){
validateScroll.init();
})
The result I am getting is "undefined", since those are appending and not caught in the DOM.
Can anyone please suggest me any process? Is there any API to get the error fields in javascript. I have searched their Javascript API, but couldn't find any such API.
I have also asked this on PDN but got no reply.
Thanks in advance.

javascript alert not working when API http request has json error (nothing found)

I'm using a thesaurus API,
http://thesaurus.altervista.org
to get synonyms to print to the page. In this demo version,
http://plnkr.co/edit/6pNYlXcgiwxHz00AY5CT?p=preview
it works when you type 'peace', otherwise, in console, if we follow the link, we see a GET error:
{"error":"the key test_only is restricted, please use your own key!"}
(EDIT: to clarify: Demo mode is not the issue. I want to make an alert.) For errors, I want the browser to alert "Oops, word not found. Please choose another word."
Here is the js code from the demo:
//function activated on user input
function myFunc(){
var userInput = document.getElementById('userInput');
var result = userInput.value;
var s = document.createElement("script");
//This demo works with the keyword 'peace' only. So searching for e.g. 'hat' will cause an error.
s.src = "http://thesaurus.altervista.org/service.php?word=" + result + "&language=en_US&output=json&key=test_only&callback=process"; // NOTE: replace test_only with your own KEY
document.getElementsByTagName("head")[0].appendChild(s);
window.process = function (result) {
//my attempt at throwing an error
if(result.error){alert("Oops, word not found. Please choose another word.");}
//normal processing..
output = "";
for (key in result.response) {
list = result.response[key].list;
output += list.synonyms+"<br>";
}
if (output)
document.getElementById("synonyms").innerHTML = output;
}
}
I did some research and found this answer (it's jQuery but mine's not but it might be relevant?):
https://stackoverflow.com/a/2568788
Any help much appreciated, thanks.
It's because you need to generate your own key. The key you are using is just a sample key.
Right there.
Then you'll change test_only is the URL by the generated key.
Anyhow, that perhaps means that the service is not free of use, so be careful and read the license if you plan to use it commercially.
You need to replace the test API key with your API key.
You can get your API key by going to http://thesaurus.altervista.org/mykey and signing up or logging in.
You even have a comment in your code telling you to do this:
s.src = "http://thesaurus.altervista.org/service.php?word=" + result + "&language=en_US&output=json&key=test_only&callback=process";
// NOTE: replace test_only with your own KEY
So if your API key 123456789, your URL will look like this:
s.src = "http://thesaurus.altervista.org/service.php?word=" + result + "&language=en_US&output=json&key=123456789&callback=process";

My node app gives diffrent output on my vps(debian) then on my local machine(windows)

I have this piece of code:
var jsdom = require('jsdom');
jsdom.env("http://sunwell.pl/index.php?id=ranking&t=2vs2&r=1",
['//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'],
function(error, window){
if(error) {console.log(error); return;}
var $ = window.$.bind(window);
var _ladder = [];
$("#rankingtable tr").each(function(i, v){
console.log('one more...');
_ladder[i] = [];
$(this).children('td').each(function(ii, vv){
_ladder[i][ii] = $(this).text();
});
});
console.log(_ladder);
window.close();
}
);
http://pastebin.com/eS4xyDrD.
Which well, works perfectly fine on my local machine(Windows), giving the expected 'one more..' text a few times and then the full array.
The problem comes when I run it on my VPS(debian onboard) which outputs just an empty array. I checked if maybe my server could for some reasons not recive the jquery object or the site but everything seems just fine. I don't know how to fix this, thanks for any help I am pretty sure the issuse is banal.
This is probably because you run into a Cloudflare Challenge page.
Try to output window.document.title, you should get a Attention Required! | CloudFlare in the <title>. You either need to find a way to solve the captcha, or get the site owner to whitelist your IP on Cloudflare.

Categories

Resources