Tidio Javascript Api – Delete message history

I need to delete the message history through the Tidio API, in its documentation there is not much information

Link: https://docs.tidio.com/docs/other_methods

Where can I find more details of the methods available to do this, is this possible via the API?

With this code you can show the chat window:

function() {
  function onTidioChatApiReady() {
    window.tidioChatApi.hide();
    window.tidioChatApi.on("close", function() {
      window.tidioChatApi.hide();
    });
  }

  if (window.tidioChatApi) {
    window.tidioChatApi.on("ready", onTidioChatApiReady);
  } else {
    document.addEventListener("tidioChat-ready", onTidioChatApiReady);
  }

  window.addEventListener('load', (event) => {
    window.tidioChatApi.show();
    window.tidioChatApi.open();
  });
  
})();

postman returns correct data, but using browser returns a unauthorized error

I’m currently creating a 3rd party webapp which fetches from an api. when using postman and providing the correct headers, I get all the information I need, but when I try to make postman issue the request on my backend server, which then asks for the info, I get an unauthorized error.

Normally on Postman I do a get request with ‘the link’ and then pass in the headers, authorization and x-auth-token, and this outputs the right data. When switching over to my backend server that runs on localhost:3001,I instead ask postman to make a get request from ‘localhost:3001/search’ and pass the same exact headers as the working postman code

Here is my code:

server.js

const express = require('express');
const bookings = require('./routes/bookings.js');
const requests = require('./routes/requests');
const search = require('./routes/search');
const auth = require('./routes/auth')
const cookieParser = require('cookie-parser')
const mongoose = require('mongoose')

const server = express();

const port = 3001
// set bodyparser
server.use(express.json());
server.use(cookieParser())
server.use(express.urlencoded({extended: true}))

server.listen(port, () => {
    console.log(`Server running on port: ${port}`);
});
mongoose.connect(
    process.env.DBHOST,
    {
        useUnifiedTopology: true,
        useNewUrlParser: true
    }
).catch(error => console.log(error));

server.use('/bookings', bookings);
server.use('/requests', requests);
server.use('/search', search);
server.use('/user', auth)

mongoose.connection.once('open', () => console.log("Connected succesfully to MongoDB"))
module.exports = server

search.js

const express = require('express')
const router = express.Router()
const axios = require('axios')
require("dotenv").config({ silent: true })

router.get("/",(req,res) => {
    axios
        .get(`the link`)
        .then(apiResponse => {
            res.json(apiResponse.data)
        })
})

module.exports = router;

this returns a 419 response Unauthorized error. I’ve also tried making my front-end pass the same headers to my back-end server through another axios call, but this is to no avail. Any help would be greatly appreciated.

How to draw dynamic number of Plotly graphs with dynamic data

I am working with VueJs and plotly and understand how to draw 1 plot. I am going to be getting a dynamic number of objects ranging anywhere from 1 through 20, and I need to create individual graphs for them once the data arrives.

The issue I am seeing is that you must have the trace’s and filled area in the data() section for a individual graph. Because it’s bad practice to hardcode upto 20 different graph objects in here I am searching for a clean way to achieve this effect in Javascript working with VueJS 2.0.

Render “Transaction Forms PDF Layouts” in NetSuite – Missing logo and 2 other fields

I have user event script which loads button on invoice which calls clients script and direct it to suitelet. I am able to print the PDF using advance PDF template but I am missing Logo and 2 other fields.

Suitelet:

define(['N/render', 'N/record', 'N/xml'], function(render, record, xml) {
      function onRequest(context) {
      
          var response = context.response;

           if (context.request.method == 'GET'){

          var ifid = context.request.parameters.custparam_ifid;
          var pdfFileName = "Invoice";
          var renderer = render.create(ifid);
          renderer.setTemplateByScriptId("CUSTTMPL_129_423403_SB5_175");
          renderer.addRecord( 'record' , record.load({
              type: record.Type.INVOICE,
              id: ifid
           })
          );
          
          //context.response.setHeader({
          //  name: 'content-disposition',
          //  value: 'inline; filename="' + pdfFileName + '_' + ifid + '.pdf"'
          //});
          //context.response.writeFile(renderer.renderAsPdf());
          
        }
        //Obj.save()
       // renderer.renderPdfToResponse();
        var newfile=renderer.renderAsPdf();

        context.response.writeFile(newfile, true);
           }
      
           return {
              onRequest: onRequest
          };
      });

PDF Using Suitelet:
enter image description here

PDF using regular NetSuite Print button on invoice:
enter image description here

‘this’ is misbehaving (again) inside an ES6 method

Just getting started with ES6 classes. As far as I understood it, this was supposed to behave predictably inside a class and always point to the object. However, that doesn’t seem to be the case:

class BodyPixController {

    #target; //Declare a private property

    constructor(target){
        this.#target = target; // Set the property

        console.log(this); // logs: BodyPixController {#target: 'photo'}

        addEventListener('load', this.init); // Calls the method
    }

    init() {
        console.log(this); // logs: Window {window: Window, self: Window, document: document, name: '', location: Location,…}
        const img = document.getElementById(this.#target); // Throws error: Cannot read private member #target from an object whose class did not declare it
        console.log(img);
        async function loadAndPredict() {
            const net = await bodyPix.load( /** optional arguments, see below **/ );

            const segmentation = await net.segmentPerson(img);
            console.log(segmentation);
        }
        loadAndPredict();
    }
}

In the code above, this only points to the instantiated object inside the constructor. As soon as the init() method is called, this points to Window. Why? And how do I access private properties from inside methods?

Getting values from 2 APIs and comparing them

I am trying to make a simple program to get the latest version from the GitHub API and compare it to a local JSON file. I have jQuery to make getting the information easier. If the version from the API is different from the local file, this script should print out that it is out of date in the console. But I keep on getting errors with the program not being able to read the variables, I tried making Cversion and Lversion to global variables putting it under window so you could call it with window.Cversion, but it still returned with undefined. I tried declaring the variables before like var Lversion;, but same thing, undefined. Any tips?

This is the code for the main index.html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <p>Latest release: <span id="tag_name">Loading...</span></p>
    <p>Current release (the site): <span id="version">Loading...</span></p>
    <p>Is this site up to date? <span id="uptodate">Loading...</span></p>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
      $.getJSON("https://api.github.com/repos/3kh0/3kh0.github.io/releases/latest", function (data) {
        window.Lversion = data.tag_name;
        document.getElementById("tag_name").innerText = Lversion;
      });
      $.getJSON("about.json", function (cur) {
        window.Cversion = cur.version;
        document.getElementById("version").innerText = Cversion;
      });
    </script>
    <script>
      if (window.Lversion === window.Cversion) {
        console.log("Up to date! " + window.Cversion);
        document.getElementById("uptodate").innerText = "Yes";
      } else {
        console.warn("Out of date, latest version: " + window.Lversion);
        document.getElementById("uptodate").innerText = "No";
      }
    </script>
  </body>
</html>

about.json

{
  "version": "v3-22.11.28"
}

Send message to background.js from options.js in Chrome Extension

I can find plenty of questions for sending a message from Bbackground to content scripts or from popup to background scripts, but I can’t find any on how to send a message from options.js (triggered from my options page) to background.js for my Chrome extension

manifest.js

{
  ...
  "manifest_version": 3,
  "permissions": [
    "alarms",
    "contextMenus",
    "notifications",
    "storage"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  },
  "options_page": "options.html",
  "icons": {
    "48": "/assets/icons/icon-48.png",
    "128": "/assets/icons/icon-128.png"
  }
}

Code in options.js

// Trigger an update
chrome.runtime.sendMessage('', {
  type: 'update'
});

Code in background.js

// Listen for messages
chrome.runtime.onMessage.addListener(data => {
  console.log(data);
  if (data.type === 'update') {
    scheduleRequest();
  }
});

But nothing is happening

I’ve tried using tabs.sendMessage, but even if I put tabs in permissions it tells me that it isn’t defined when I add it to the function chrome.tabs.sendMessage(tabs[0].id, {...

Find the first match between 2 objects

I have 2 objects

const obj1 = {
    item1: {
        name: '1'
    },
    item2: {
        name: '2'
    }
}

const obj2 = {
    item1: {
        sample: 'sample1'
    },
    item2: {
        sample: 'sample2'
    }
}

How can I loop over the second object obj2, find the first match against object obj1 and return it?

In above example, I should return

{
    item1: {
        name: '1'
    }
}

since item1 is the first match between the 2 objects and I want what’s inside obj1.

Tried the following:

const keys = obj2 && Object.keys(obj2);

const output = () => {
    if (keys) {
        const finalResponse = keys.map(key => {
          if (obj1[key]) return obj1[key];
          return undefined;
        });
    }
}

But ends up undefined even though there is a match on item1.

What am I doing wrong and is there a cleaner way to do this.

Fine to loop over obj1 or obj2 as long as I can return the match in obj1.

Fabric.js with React – cannot change to drawingMode

I’m trying to change some of the fabric.Canvas object properties on button clicks.
When I consol.log properties after change everything seems fine, but it doesn’t have any effect on drawing. Adding objects works but with some unexpected behaviour.

This is the component where I render my canvas:

export const WhiteboardBox: FC<WhiteboardBoxProps> = ({}) => {
  return (
    <div>
      <WhiteboardTools />
      <canvas id="fabricCanvas" />
    </div>
  );
};

It renders WhiteboardTools which should handle drawing, adding objects etc.:


let canvas: Canvas;
export const WhiteboardTools: FC = () => {
  const [color, setColor] = useState("blue");

  useEffect(() => {
    canvas = new fabric.Canvas("fabricCanvas", {
      height: 900,
      width: 1600,
      backgroundColor: "white",
    });

    canvas.isDrawingMode = true;
  }, []);

  useEffect(() => {
    canvas.freeDrawingBrush.color = color;
  }, [color]);

  const testChangeColor = () => {
    setColor((color) => (color === "red" ? "blue" : "red"));
  };

  const testObjectAdd = () => {
    canvas.add(
      new fabric.Rect({
        width: 50,
        height: 50,
        fill: "green",
      })
    );
    canvas.isDrawingMode = false;
    canvas.renderAll();
  };

  const testDrawingOff = () => {
    canvas.isDrawingMode = false;
  };

  const logCanvasProps = () => {
    const { isDrawingMode, freeDrawingBrush } = canvas;
    console.log({ isDrawingMode, freeDrawingBrush });
  };

  return (
    <div className={styles.container}>
      <div>
        <button onClick={testChangeColor}>change color</button>
        <button onClick={testObjectAdd}>Add obj</button>
        <button onClick={testDrawingOff}>Drawing off</button>
        <button onClick={() => logCanvasProps()}>Print</button>
        <>State color: {color}</>
      </div>
    </div>
  );
};

There are two main issues which I cannot solve:

  • changing canvas.isDrawingMode property doesn’t do anything (even though it is changed when I log it).
    Same when I set a color state – useEffect fires, but doesn’t have any effect on actual drawing color,
  • testObjectAdd (the only method which actually changes canvas) spawns rectangle which I want, but all previously drawn stuff disappears. Then, when I draw something, that stuff comes back, but my rectangle disappears…

I’m declaring canvas outside of component because this is what I saw people doing (and working for them).
I also tried with it being a state either insinde WhiteboardBoxor WhiteboardTools with same results.

Serialising an HTML element that has event handlers

I am currently making a website for a class that I am in. It is supposed to be a store, made in Pure HTML, CSS, and JavaScript (no libraries including jQuery). I am currently attempting at making a functional cart right now. My idea is to take the element that has the information about that item (image and name, but price I kept to be constant throughout to make it simpler). From here, I thought about serialising that element and saving it to localStorage so that I can load it from the cart page. When I try JSON.serialize(product) where product is the element of the item, it only ends up with "{}" and nothing else. XMLS.serialiseToString() only gives the element without the event handler. How am I supposed to make this work?

I also tried loading the event handler in the cart page too, but I cannot figure out a way to get the HTML element from a string. Could someone tell me how to make this work? I looked at a few other questions on here but it does not make much sense to me.

How to get user picture from their google account with NEXT.js Image

Hello I am trying to get user picture from Google to NEXT’s <Image>

<Image src={user?.photoURL} alt="user picture" width={50} height={50} className="rounded-full ml-5" />

which gave me this error

Error: Invalid src prop (https://lh3.googleusercontent.com/a/ALm5wu3hfqfP7bHOGlGE5RXeB-2efMFGK3IZidD5RRGe=s96-c) on `next/image`, hostname "lh3.googleusercontent.com" is not configured under images in your `next.config.js`
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host

so I add this to next config


 images: {
    remotePatterns: [
      {
        hostname: "**.googleusercontent.com/**"
      }
    ]
  }

but it still doesn’t work.

Setting my value to usestate after clicking second time first gets assigned there

It is so that I get a problem like doing that when I write email for the first time and it is sent in the database. Then I expect something to come back. Which also do. But it adds nothing to my usestate at all. But when I try to click again and write email again. Then the message I expected is added to my usestate.

So after the second time I have clicked it works exactly as it should and I want them to but it does nothing the first time.

Here you can see my html part for the react.tsx file.

<form onSubmit={(e) => submitClick(e)}>
    <label className='labelValue'>Email</label>
      <input
      type="text"
      className='w-full border-2 border-slate-100 p-2 md:rounded-lg mt-1 md:mt-2'
      value={email}
      onChange={(e) => setEmail(e.target.value)}
      placeholder='Email here' />
    <button disabled={disabledNow} className='btn w-full'>
       {disabledNow ? "Account are createde now." : "Create user"}
    </button>
</form>

Here can u see my React for at post to database in my react.tsx file.

const [email, setEmail] = useState('');
const [dataValue, setDataValue] = useState([]);
const [item, setItem] = useState(0);
const [disabledNow, setDisabledNow] = useState(false);

const submitClick = (e) => {
  e.preventDefault();
  setItem(1);
  setDisabledNow(true)
}

useEffect(() => {
  const dataMail = {
    Email: email
  };

  let ignore = false;
  if (item === 1) {
    if (!ignore) {
      const fetchData = async () => {
        const result = await axios.post("https://localhost:7176/api/user", dataMail)
        const fetchItem = await result.data;
        setDataValue(fetchItem);//not adding fetchItem first time i make a click onSubmit. But after this i get a fetchItem to setDataValue.
        console.log(dataValue);
      }

      fetchData();

      setEmail('');
      setItem(0)
      ignore = true

      if (dataValue.length > 0) {
        console.log("Out of Fetch now. HERE")
        toast(dataValue[1], { duration: 7000 })
        console.log("Notify now HERE")
      }
    }
  }

}, [dataValue, email, item])

As I said, I have also tried to remove async and await and it still gives the same problem that I don’t have it on.

Unable to list event object properties [duplicate]

Sorry if this is a duplicate, but I searched and cannot find the information I am looking for. I’m learning about the javascript event object:

Why can’t I list all of the event object properties using Object.keys() or getOwnPropertyNames()? I expected them to list all accessible properties on the event object.

e.g. (look below for source or checkout the code-pen if you prefer):
https://codepen.io/dleskydev/pen/GRGXwpr?editors=1011

<button> Click Me </button>

let button = document.querySelector("button")
button.addEventListener("click", listProperties) 

function listProperties(event) {
  console.log(`keys:  ${Object.keys(event)}`).  //keys: isTrusted
  console.log(`property names: ${Object.getOwnPropertyNames(event)}`) // property names: isTrusted
  console.log(`type:  ${event.type}`) // "type:  click"
  console.log(`button:  ${event.button}`) //// "button:  0"
}

I’m assuming that “event.target” or “event.type” or “event.button” aren’t properties in the usual way that we think about them, but I have no additional insight into why. Instead of checking the reference for each event type, I figured it would be nice to just list all the associated properties, but all I get is the value of the ‘isTrusted’ property.
Clearly ‘type’ and ‘button’ are accessible properties on the event object, yet they do not appear with Object.keys(event) or Object.getOwnPropertyNames(event)…

Thanks for your help!
Dan

How to log output in cypress cucumber html report?

I am using @badeball/cypress-cucumber-preprocessor for my automation. I am looking for how to print output/log in html report. In Cucumber-Java I have scenario.write("hello"); statement to print messages in cucumber html report. Likewise how can i print in Cypress-Cucumber report?