Ways to resolve the issue of inline JavaScript invocation error in chrome-extension

I am currently working on a chrome extension, but I am encountering an error when trying to activate an onclick() event.

Refused to load the script 'https://apis.google.com/js/client.js?onload=handleClientLoad' because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:"

Additionally,

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". To enable inline execution, either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is necessary.

This is the content of my manifest.json :

{
  "manifest_version": 2,

  "name": "SECURE",
  "description": "this extension offers secure communication for GMAIL users",
  "version": "1.0",

 "browser_action": {
 "default_icon": "resources/icon16.png",
 "default_popup": "popup.html",
 "default_title": "Click here!"


 },

 "background":{
   "scripts":["background.js"]
},

 "content_scripts": [
  {
   "matches": ["http://*/*", "https://*/*"],
   "js":["myscript.js"],
   "run_at": "document_end"
  }
  ],
"permissions": ["identity", "https://accounts.google.com/*",  "https://www.googleapis.com/*"],

"oauth2": {
   "client_id": "975410329966.apps.googleusercontent.com",
 "scopes": [
   "<all urls>",
   "https://www.googleapis.com/auth/drive",
   "https://mail.google.com/",
   "https://www.googleapis.com/auth/gmail.login",
   "https://www.googleapis.com/auth/gmail.compose",
   "https://www.googleapis.com/auth/gmail.readonly",
   "https://www.googleapis.com/auth/gmail.send"
  ],

 "content_security_policy":"script-src 'self'  'unsafe-inline' 'unsafe eval'  https://apis.google.com/js/client.js?; object-src 'self'"


}
}

If anyone has any advice on how to resolve this issue, I would greatly appreciate it.

Answer №1

By default, according to the Content Security Policy, inline scripts are not loaded and only local scripts can be allowed. You have the option to modify this policy by:

  1. Inline Script: Refer to the Official Guide. Inline scripts can be permitted by specifying the base64-encoded hash of the source code in the policy. For an example, check out Hash usage for elements.

    However, it is recommended to extract this logic into a separate script rather than using inline scripts.

  2. Remote Script: You can whitelist remote script resources like

    https://apis.google.com/js/client.js?onload=handleClientLoad
    by adding the following section to your manifest.json:

    "content_security_policy": "script-src 'self' https://apis.google.com; object-src 'self'"
    

    Alternatively, consider downloading the remote client.js file and include it as a local script.

It is important to note that, as mentioned in the explanation of Inline Script, using unsafe-inline is no longer effective.

Prior to Chrome 45, there was no way to relax the restriction on executing inline JavaScript. Specifically, including 'unsafe-inline' in a script policy will not work.

Answer №2

To address this issue, I decided to streamline the process by moving all functions into a JavaScript file. Rather than having the onclick method directly in the HTML code, I transferred it to the JS file:

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("button").addEventListener('click', <function>);
});

Answer №3

Replace the onclick function with this code in a separate file:

document.getElementById("#divId").addEventListener("click", myFunction);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to building a JavaScript array and storing data from a separate array into the newly created array in JavaScript

Can you help me create a JavaScript array and save another array of data to be part of the newly created array in JavaScript? I attempted it using the code below. Code: var vvv=this.new_products.length-this.quote.lines.length; let mmm={}; if(v ...

developing a seamless and uncomplicated banner text animation

Greetings everyone! I am diving into the world of JavaScript and recently attempted to create a banner carousel animation. Specifically, I have 3 banners in rotation where each slide reveals text with an animation effect. However, I'm encountering an ...

Updating Django database records with ajax

I'm currently working on a feature that involves filtering table data and updating the table using ajax. Here's what I have so far: Filter Form: <form id="search" method="POST" action="{% url 'article-filter' %}"> <input ...

The componentDidMount lifecycle method of a rendered component in a Route is not being triggered

IMPORTANT: SOLUTION PROVIDED BELOW, NO NEED TO READ THROUGH THE QUESTION I am utilizing the following Router with react-router 4 return ( <Router> <Page> <Route exact path="/" component={HomePage} /> <Route path="/c ...

Updating Variables in Azure DevOps Code Prior to DeploymentORModifying Variables

Can Azure DevOps automate code updates upon release? For instance, in my React app, I have a setting file with export const ISPROD = false. I want Azure DevOps to modify this value to true before building and deploying the app. Is this achievable? Please ...

Is there a correct way to accomplish this task? How could I go about achieving it?

Currently, I am delving into the world of react. While following along with some video tutorials, I encountered a roadblock in the request.js file. The issue popped up during the build process ./src/Row.js Line 16:45: 'fetchUrl' is not define ...

Switch out the play pause button on an embedded YouTube video player

Is it possible to customize the play/pause button on YouTube iframes using CSS? I have several iframes and would like to change the default red play button. I've attempted the following code: .ytp-large-play-button{ background: url(play.png); } ...

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

"Create a dynamic entrance and exit effect with Tailwind CSS sliding in and out from

My goal is to create a smooth sliding animation for this div that displays details of a clicked project, transitioning in and out from the right side. This is my attempt using Tailwind CSS: {selectedProject !== null && ( <div classNam ...

Experiencing a blank array when using filtering/search text in a Nodejs application with MongoDB

I am experimenting with search functionality in a MongoDB database using Node.js. However, my result array is always empty. I have shared my code here and would appreciate some assistance in identifying the issue. Whenever I perform a search, I end up with ...

Enhance Your Website with GatsbyJS Custom Scrollbars

I'm struggling to customize the default scrollbar on my Gatsby website with an overlay scrollbar. I want to avoid the page 'shifting' slightly to the left when switching between pages that have scrollbars and those that do not. My attempt i ...

When configuring three.js and node.js on a live server, encountered a SyntaxError due to an unexpected string while importing './style.css'

Having trouble getting a simple three.js website up and running on a live server (a2 shared hosting). Node.js is installed, but the start up file main.js doesn't seem to be reading properly. Completely new to Node. Starting the server results in an er ...

Tips for activating text selection in PDF.js

Struggling to enable text selection in PDF.js after successfully displaying a PDF? Seeking a simple example to guide you through the process? Despite trying various approaches, I haven't achieved the desired outcome yet. My current code snippet is a ...

I am receiving a high volume of row data from the server. What is the best way to present this information on a redirected page?

There is a scenario where Page 1 receives a substantial amount of row data in JSON format from the server. The goal is to present this information on Page 2, which will be accessed by clicking on Page 1. To accomplish this task, JavaScript/jQuery and PHP ...

When you click on the image link, watch as the page gracefully transitions to a new one determined by the URL

I need assistance with a functionality where an image inside a div has a link to the next page. When this image is clicked, it should smoothly transition to the new page specified by its link. Any help with implementing this would be greatly appreciated. ...

obtaining user information from API using the x-api-key

As a beginner JavaScript programmer, I'm attempting to fetch user information. Is there a simple way to search for a specific person like Laurel Gates with the USERID: 987654321? English is not my native language, so I apologize for any mistakes. Here ...

Could someone help with why the target id is not being properly passed when clicking on a li

Currently, I am working on a ReactJS project utilizing MaterialUI. The code snippet I am dealing with is as follows: { this.state.categories.map((category, key) => ( <List> <ListItem button id={key} onClick={this.handleClick}> ...

Turn off the feature that prohibits the use of variables before they are

I'm struggling to disable this setting in my tsconfig file. The TS documentation doesn't seem to have any information about how to do it. no-use-before-declare I'm facing an issue where my test stub data objects are interfering with each ot ...

What could be causing the undefined status of my checkUser() function?

I have implemented a brief script on my signup page to define the function checkUser(user) at line 6. In the code section at the end of the HTML for the sign up form, I included an inline script onBlur='checkUser(this) within the <input> named ...

The success callback function in jQuery.ajax() sometimes receives undefined parameters

In my current code, I am using an ajax call to communicate with a Wordpress file responsible for creating WP users. jQuery.ajax({ method: 'POST', dataType: 'json', url: ajax_object.ajax_url, // Post ...