Google Web Apps send current html page body to email as a pdf

I am using Google web app, I have a html form, collecting data, I am trying to send the current pages body as a PDF attached on an email.

code.gs

function sendMail(myhtml) {
  
        var blob = Utilities.newBlob(myhtml,MimeType.HTML);

        var options = {'attachments' : 
                       {'fileName' : 'test',
                        'mimeType' : 'application/pdf',
                        'content' : blob.getBytes()
                       }
                      };
        MailApp.sendEmail("myemail address", 'Subject','', options)
      
}

HTML page

loginForm.addEventListener("submit", (e) => {
  console.log("Button Pressed")
    body = document.getElementsByTagName('body').innerHTML;
    console.log(body)
 google.script.run.sendMail(body)

authenticated users are sent to correct route but need to refresh to see the page

so i am building a simple transaction application to build my skills and i am new to authentication i am using localstorage to create “tokenn” item whenver a user signs in/ signs up
I want to check if the user has tokenn then they should not access the signin signup pages (ie redirected to the Dashboard page) and vice verca for not having the tokenn

i did hell lot of things to tackle tried conditional rendering, tried to add a authCheck component to components which should be shown to signed users etc etc
but everytime i came to two things

  1. not working
  2. working but need to refresh (in both cases ie when unauthenticated users try to navigate to Dashboard and other components as well as authenticated users try to navigate to signin and other components)

here is the App.jsx code where i tried
app.jsx

i also tried checking if the token exists then show this else this and various other things but nothing is working

If someone can help me with this it would be really really appreciated
also heres the git repo for this : frontend
live

How do I select a “random” MUI palette color?

Say I have a chart series, or some other component that can take on a wide range of values that I’d like to colorize by value, but for which the color doesn’t have any semantic information (i.e. it’s not “success”, “error”, “warning”, etc.) What’s the best way to select a “random” color that looks good with my MUI palette?

Is there a way to implement render reactivity in a Lit directive?

I’m using Lit 2.7.6 and am trying to implement a directive that can be used inside of a component. I tried to get a working StackBlitz example to share, but there was an issue with the imports from the lit packages that I couldn’t get working.

The issue I’m encountering is that updating the isOpen property doesn’t actually trigger a re-render inside of the directive, but does inside of the component. For example, if this directive was used to open a menu, the isOpen prop would change, and you could see it in a console.log, but the actual render of ${is.Open} on the page would not change.

This is my component.ts file,

import { LitElement } from 'lit-element';
import { html, TemplateResult } from 'lit';
import { property } from 'lit/decorators.js';
import { exampleDirective } from './directive';

class exampleComponent extends LitElement {
  @property({ type: Boolean })
  isOpen: boolean = false;

  render(): TemplateResult {
    const props: Object = {
      isOpen: this.isOpen,
    };

    return html`
      <div>${this.isOpen}</div>
      ${exampleDirective(props)};
    `;
  }
}

And this is my directive.ts file,

import { html, TemplateResult } from 'lit';
import { Directive, directive, PartInfo } from 'lit/directive.js';

class directiveTemplate extends Directive {
  private props: Object;

  constructor(partInfo: PartInfo) {
    super(partInfo);
  }

  update(partInfo: PartInfo, [props]: [Object]) {
    console.log(props);
    return this.render(props);
  }

  render(props: Object): TemplateResult {
    return html`<div>${props.isOpen}</div>`;
  }
}

export const exampleDirective = directive(directiveTemplate);

eval vs Function() return semantics

Disclaimer: The code mentioned in the question is assumed to be running in the trusted environment (not the browser), and the code itself is trusted. So any security considerations about eval are not applicable. The main goal of the question is to prevent pollution if the global scope performed by the eval.


When using the eval, then the result of the last expression is considered as the return value of the whole eval, e.g. result of the eval-ing of the following code will be the value of the y+2=12 expression.

var res = eval("
    var x = 5;
    var y = x*2;
    y+2;
"); //res = 12 

At the same time, if we will wrap such a code into the Function constructor, then the result will be undefined

var res = (new Function("
    var x = 5;
    var y = x*2;
    y+2;
")).call(); //res=undefined

To fix the last snippet, we need to add explicit return to the last expression:

var res = (new Function("
    var x = 5;
    var y = x*2;
    return y+2;    // <------- changes here
")).call(); //res=12

So, the eval and Function have the different return semantics.

And I can’t just replace replace eval with the Function() in the some legacy code. I will also be forced to change the calling side to add the return in the code, passed to Function().

Is there a way to avoid adding explicit return, so it will be possible to replace eval with the Function() in a transparent way (let’s assume that we are not interested into the access to the local scope)?

Or may be there is another technique exists, which can provide the equivalent of the eval which will minimise the risks of the global scope pollution and will provide the same return semantics as the original eval?

Note: The JS engine used in the system is quite old, so it does not support strict mode and ES6+ features.

Validation JavaScript code in “onsubmit” form attribute blocking my post request

I’m trying to send a post request using Python. I’m using a requests.Session() object.

All the required fields to make up the payload (as per the network tab) come from a form itself in the html code, which I can easily retrieve.

The problem (I think) is that the form contains an onsubmit attribute with some js code as follows

onsubmit="if(getBlocked()==true){return false;}setBlocked(true);"

…which I think is preventing my post request from working properly, as I get constantly redirected to an erro page.

There’s a few js filed being loaded when the page gets loaded, which define the element “Blocked” itself and define getters and setters for this element. But of course this js code isn’t being loaded when I make the post request.

My question is: how can I make this post request to work?

Thanks in advance

Cursor moving inside input after formatting

I’m using Angular 16 with TypeScript and tailwind.
I’m building an Input which is supposed to store percentage value, so min 0 and max 100. The request is to have it showed with two numbers after the comma.
This is my actual input:

    <div class="flex">
      <span class="text-primary text-left px-2 border-b border-[#E0E0E0] w-3/4">
        <input
          class="text-3xl w-full"
          type="number"
          matInput
          placeholder="0.00 %"
          required
          [(ngModel)]="pointsEstimatedUtilization"
          (ngModelChange)="onEstimatedUtilizationInputChange()"
          oninput="this.value = Math.min(this.value, 100).toFixed(2)"
        />
      </span>
      <span class="w-1/4 flex justify-center items-center text-xl">%</span>
    </div>

What happens is that as default is displayed 0 (it’s fine for me), if I write for example a ‘1’ before the 0, it gets correctly formatted as 10,00, but the problem is that the cursor went to the end of the input, so just after the two zeros.
For example, if I’ll have to write for instance 50, straight after I press 5 the cursor goes to the end, leaving the input something like 5,00 and without allowing me to write anymore (because there is the toFixed(2), because after the cursor moved it was like I was adding the 0 at the end like 5,000)

Is there a way to keep the cursor where it is and still getting it formatted?

HttpClient in Angular request does not start

Introduction:
A button in a form invokes a method named methodForm in the component.
methodForm in turn calls a method named methodService in the service layer.
methodService should make an HTTP POST call.
Issue:
The HTTP POST call is not happening.
methodService is still invoked, as confirmed by a console.log.
Question:
Why is the HTTP POST call not being executed?
What could be the reasons and possible solutions?
Additional Information:
I attempted to typecast the Observable with interfaces type.
I tried using the JSONPlaceholder APIs, but without success.
I am using standalone Angular components.

register.component.html

<button
            class="w-100 btn btn-primary btn-lg"
            (click)="register()"
            [disabled]="form.invalid && form.submitted">
            Continua la registrazione
          </button>
          <div class="mt-2 text-center">
          <small 
            *ngIf="form.submitted && form.invalid"
            class="form-text text-danger">Il form non è valido. Controlla i campi
          </small>
        </div>

register.component.ts:

export class RegisterComponent implements OnInit {
  @ViewChild('form') form!: NgForm;
  grantValue!: number;
  grantUser: number = 2;
  grantClient: number = 3;
  private __genericUser: GenericUser = new GenericUser;
  italianProvinces: string[] = [...];
  selectedProvince: string = '';
  maxDate!: string;

  ngOnInit(): void {
    this.genericUser.gender = "";
    this.genericUser.grant = 0;
    this.genericUser.province = "";
    const today = new Date();
    const year = today.getFullYear();
    const month = ('0' + (today.getMonth() + 1)).slice(-2);
    const day = ('0' + today.getDate()).slice(-2);
    this.maxDate = `${year}-${month}-${day}`;
  }

  constructor( private service: RegisterService, private router: Router){
  }

  set genericUser(genericiUser: GenericUser){
    this.__genericUser = genericiUser;
  }
  get genericUser(): GenericUser {
    return this.__genericUser;
  }
  
  register(): void {
   if(this.form.invalid){
      this.service.register(this.__genericUser);
    } else {
      this.router.navigateByUrl('');
    }
    }
}

register.service.ts:

@Injectable({
  providedIn: 'root'
})
export class RegisterService{
  apiurl = environment.API_URL_REGISTER_USER;
  api = 'https://jsonplaceholder.typicode.com/posts'
  constructor(private http: HttpClient) {}

  register(__genericUser: GenericUser): Observable<GenericUser> {
    console.log("stop");
    return this.http
      .post<GenericUser>(this.apiurl, __genericUser)
      .pipe(map((resp) => resp));
  }
}

app.config.ts:

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes), provideHttpClient()],
};

Problem with turning off barcode scanning when the browser is closed or the browser goes to the background on mobile at Html5-Qrcode

While using html5-qrcode on mobile or desktop, if the user closes the browser or changes the browser tab without stopping the html5-qrcode in scanning mode, html5-qrcode still uses the camera source as if it were scanning. This creates problems in my own application. Is it possible to stop html5-qrcode in scanning mode if the user closes the browser or puts it in the background on the mobile app or if the browser tab changes? What can be done for this in best practice? Or is there an integration for this need within the module? I would like to point out that I would like to thank the people who made this open source application. It saved me from buying a paid module.

Modele Github:
Html5-Qrcode

Access an element hovered using mouseEnter and mouseLeave (JS only)

I created a NavBar which has 5 links and tried to make an animation which consists of 2 lines that appear at the top and bottom of a link whenever it is hovered. Moreover, I’d like it to not only appear but also move from one link to another (at the condition where several link are hovered without leaving the Navbar, else it disappears) smoothly.

Here is the code :

HTML :

<div class="head_nav_bar">
            <p class="nav_brand_name">La Mariée Futée</p>
            <nav class="navbar">
                <a href="" class="nav_item" id="navitem1">Notre Histoire</a>
                <a href="" class="nav_item" id="navitem2">Nos partenaires</a>
                <a href="" class="nav_item" id="navitem3">Astuces</a>
                <a href="" class="nav_item" id="navitem4">Témoignages</a>
                <a href="" class="nav_item" id="navitem5">Nous Contacter</a>
            </nav>
        </div>

CSS :

.head_nav_bar{
    background-color: #27120A;
    position: sticky;
    display:flex;
    width: 100%;
    height: 16vh;
    align-items: center;
    scroll-snap-align: start;
    color: #ffffff;
    z-index: 1;
}

.navbar{
    background: linear-gradient(to left, #d9d9d910 30%, #d9d9d900 80%);
    width: 100%;
    margin: auto;
    padding-left: 35%;
    font-size: 32px;
    position: relative;
}

.navbar a{
    color: #ffffff;
    margin: 0.1em 1em;
}

.nav_brand_name{
    position: absolute;
    font-size: 86px;
    font-family: "Dancing Script", cursive;
    margin-left: 2%;
}    

.nav_item{
    display: inline-block;
}

And JS :

const navItems = document.querySelectorAll('.nav_item');

navItems.forEach(navItem => {
    navItem.addEventListener('mouseenter', function() {
        const boundingBox = this.getBoundingClientRect();
        const navbar = document.querySelector('.navbar');
        const lineTop = document.createElement('div');
        const lineBottom = document.createElement('div');

        lineTop.classList.add('line');
        lineBottom.classList.add('line');

        lineTop.style.top = boundingBox.top + 'px';
        lineBottom.style.top = boundingBox.bottom - 2 + 'px';

        navbar.appendChild(lineTop);
        navbar.appendChild(lineBottom);

        setTimeout(() => {
            lineTop.style.width = boundingBox.width + 'px';
            lineBottom.style.width = boundingBox.width + 'px';
        }, 10);

        this.addEventListener('mouseleave', function() {
            lineTop.style.width = '0';
            lineBottom.style.width = '0';
            setTimeout(() => {
                lineTop.remove();
                lineBottom.remove();
            }, 300);
        });
    });
});

At first I tried doing it with CSS, and with success BUT I couldn’t find a responsive solution as I want the lines to be the same width as the links but those aren’t equal.

I also tried brute force, using a different (but same) function for each link (so in each function I would use getElementById(linkId) in order to get their respective width and position) and it works, but I would prefer a less brutal way.

I lastly tried ChatGPT and I came with the code presented above but I can’t seem to find any way to make it work (neither in the current website I am making nor in any test files).

How to expand numeric input validation when generating a table using rhandsontable?

I started using hot_validate_numeric() of the rhandsontable package and it is proving to be very useful for user input validation. Per the below MWE code, the user can only input numeric values ranging from 1 to 10, and if the user inputs a value outside this range or inputs an alpha character or other nonsense input, the table, nicely, rejects the input and freezes until the user inputs a value using the correct form. This works when the user either changes an existing cell or when the user adds a row. This is perfect!

However, how do I expand this so the validation check is also for: (1) any input into a cell must be greater than the value in the immediate cell above it (except for the case of the first cell), and (2) only integers may be input (no decimal values)? Ideally, the response would be the same as when using hot_validate_numeric(...), in that the input is rejected and the cell freezes until the user inputs a value using the correct sequence.

It may be the case that rhandsontable doesn’t support dynamic validation based on the value of other cells in the table directly through hot_validate_numeric(), I’m not certain.

I’ve played around with hot_validate_numeric(col = 1, choices = c(...)) but that doesn’t seem to work, will submit a bug report via GitHub.

library(rhandsontable)
library(shiny)

DF <- data.frame(X = c(1,3,5,7,10))

ui <- fluidPage(
  rHandsontableOutput("base_input")
)

server <- function(input, output, session) {
  output$base_input <- renderRHandsontable({
  rhandsontable(DF) %>%  hot_validate_numeric(col = 1, min = 1, max = 10)
  })
}

shinyApp(ui, server)

How to import a js module in a ts project, nestjs

I need to import a private js module. But I have some problem because nestJs doesn’t recognize it as a module.

I try to add declaration types files (d.ts) but I don’t know how to do that correctly.
I declare the function I need to test but I have this error …is not defined by “exports”

How to convert HTML to plain text using JavaScript or Python? [closed]

How do I convert an HTML page into plain text?

I’m developing a project where I insert a URL and the code should return the site’s content in simple, editable text format, but I’m having difficulty cleaning this HTML, eliminating the menus, footer, everything that isn’t the content itself. Any ideas on how to do it?

I’ve already tried to select content cleaning by selecting content that was within the “main” tag, but not every site follows the best SEO standards and therefore could lose some. Or do you believe that it would be a good alternative to analyze only sites that followed these SEO parameters and respected the use of the “main” tag, as this would serve as a filter for sites that had the slightest concern with the quality of the content?

Im trying to display the file but i get this error Failed to execute ‘createObjectURL’ on ‘URL’: Overload resolution failed

I have form where the user fill it and send it along with a file to the admin, and the admmin should receive the data in data grid……the inputs like name and phone and email i retrive it and display it correctly but the file i retrieve it and the filePreview also and i tried to display it but i got this error : this error Failed to execute ‘createObjectURL’ on ‘URL’: Overload resolution failed.

 const Form = () => {
      const [inputs, setInputs] = useState({
        name: "",
        phone: "",
        email: "",
        assurance: "",
        message: "",
        file: null,
        filePreview: null 
      });
      const handleInput = (e) => {
        if (e.target.name === "file") {
          const file = e.target.files[0];
          const filePreview = URL.createObjectURL(file); 
          setInputs({ ...inputs, [e.target.name]: file, filePreview });
        } else {
          setInputs({ ...inputs, [e.target.name]: e.target.value });
        }
      };
    
      const uploadFile = async (file) => {
        try {
          const formData = new FormData();
          formData.append("file", file);
          const filename = file.name;
          const response = await axios.post("http://localhost:5000/backend/upload", formData);
          console.log("File uploaded successfully", response.data);
          return filename; 
        } catch (err) {
          console.error("Error uploading file:", err);
          throw new Error("Error uploading file");
        }
      };

and this the component where i display it
name phone email and ect…..

  const [selectedFormData, setSelectedFormData] = useState({
        name: '',
        phone: '',
        email: '',
        assurance: '',
        file:'',
        filePreview:''  
        
      });

handleCellClick when i click in message cell i got this data and the file

**const handleCellClick = (params) => {
    if (params.field === 'message') {
      const { name, phone, email, assurance, file } = params.row;
      const filePreview = URL.createObjectURL(file) ; 
      setSelectedMessage(params.value);
      setSelectedFormData({ name, phone, email, assurance, file, filePreview }); 
      setOpenModal(true);
    }
  };
<Modal open={openModal} onClose={handleCloseModal} className="modal-container">
        <Slide direction="up" in={openModal} mountOnEnter unmountOnExit>
          <div className="modal-content" style={{ background: "white" }}>
            <Typography variant="h5">Selected Form</Typography>
            <p>Name: {selectedFormData.name}</p>
            <p>Phone: {selectedFormData.phone}</p>
            <p>Email: {selectedFormData.email}</p>
            <p>Assurance: {selectedFormData.assurance}</p>
            <p>Message: {selectedMessage}</p>
            <p>File: {selectedFormData.file}</p>
                
    
                <div className="action-buttons">
                  <Button variant="contained" onClick={handleCloseModal}>
                    Close
                  </Button>
                </div>
              </div>
            </Slide>
          </Modal>**