0
chrome.storage.sync.get(['player_info'], (data) => {
    console.log('search')
    console.log(data)
    // data = list of possible players 
    let player_arr = data.player_info
    for (let i = 0; i < player_arr.length; i++) {
        document.getElementById("card-wrapper").innerHTML +=
            `<div onclick="alert('clicked')" class="player_option">
                <center>
                    <div class="card-img-small">
                        <a href="#">
                            <img id=\"player_img\" src="${player_arr[i].profile_img}" class="img-responsive">
                        </a>
                    </div>
                </center>
                <div class="card-body">
                    <div id="player-name" class="price-small">
                        ${player_arr[i].name}
                    </div>`
    }
})

I am dynamically rendering some items using the code above. In the div wrapper, I added an alert function to check if it works, but nothing happens. I inspected the element, and it looked like this:

<div onclick="alert('clicked')" class="player_option">
                <center>
                    <div class="card-img-small">
                        <a href="#">
                            <img id="player_img" src="https://fmdataba.com/images/p/4348.png" class="img-responsive">
                        </a>
                    </div>
                </center>
                <div class="card-body">
                    <div id="player-name" class="price-small">
                        Paul Pogba
                    </div></div></div>

It seems like the function is embedded correctly, but the alert doesn't happen. Any help?

EDIT

Actually realized I am getting this error: Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. I am building a Chrome Extension

Dawn17
  • 7,825
  • 16
  • 57
  • 118

1 Answers1

0

In chrome apps and extentions, Content Security Policy does not allow inline javascript. So you have to put your javascript in a .js file and include it in your HTML.

You have to use js event listener instead. Take a look at this: Refused to execute inline event handler because it violates CSP. (SANDBOX)

If you still want to use js in onClick attributes, you could also change the Content Security Policy. Look at: Content Security Policy (CSP) under "Relaxing the default policy".

François Huppé
  • 2,006
  • 1
  • 6
  • 15