简体   繁体   中英

How do you send a function to an onclick button in Express and Pug?

I'm trying to send a function that can be assigned to the onclick of a button element.

On one of my pages, I'm trying to send a function named showPopup as a local variable, which I then want to assign to a button onclick..

serverController.js

exports.get_server = (req, res, next) => {
    Server.findById(req.params.id).populate("channels").exec((err, server) => {
        if(err) next(err);

        let showPopup = () => {
            let c = document.querySelector("form.container-popup#add-channel");
            c.hidden = false;
        }

        res.render("server-page", {
            server: server, 
            user: res.locals.currentUser,
            showPopup: showPopup
        })
    })
};

channel-side-bar.pug

div.secondary-side-bar
    div This is the channel side bar
    for channel in server.channels
        a(href=`/server/${server._id}/channel/${channel._id}`) #{channel.name}
        br
    button.add-channel(type="button" onclick=showPopup) Add Channel

    //- - showPopup() <-- runs my function when program runs

    form.container-popup#add-channel(method="POST" action=createChannelURL hidden=true)
        .div Create Channel
        label(for="name") Channel Name
        input(type="text" name="name" placeholder="Enter channel name here...")
        label(for="private") Private Channel?
        input(type="checkbox" value="private" name="private")

        button(type="submit") Submit
        
script.
    //- let addChannelButton = document.querySelector("button.add-channel")
    //- addChannelButton.onclick = showPopup;
    console.log("in pug script")

When I run my code, I get an error saying:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src-attr 'none'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.

Just for the record, I have also put in quotes like so:

onclick="showPopup" 
onclick="showPopup()"  

What am I doing wrong?

I have also tried adding the onclick function directly on the pug page script, but that doesn't seem to run either.

Do you try to build a Chrome extension?
If it's the case, you should read this: https://developer.chrome.com/docs/apps/contentSecurityPolicy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM