Struggling with loading external scripts within background.js in Chrome extensions?

I am facing an issue with my chrome extension. I am unable to call an external script, specifically the ethereum script (web3.min.js), from within my background.js file. The error message I receive is:

    Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' blob: filesystem:".

Here are the steps I have taken so far:
1. I tried downloading the script and adding it to the extension folder, as well as to the manifest.json file:

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

While this method added the script successfully, I still encountered the same error due to dependencies within the included file. 2. I attempted to use XMLHttpRequest to fetch the script:

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://cdn.jsdelivr.net/gh/ethereum/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="196e7c7b2a37736a592837293729347b7c6d78372a2d">[email protected]</a>/dist/web3.min.js", true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
          var resp = eval("(" + xhr.responseText + ")");
      }
    }
    xhr.send();
  1. Lastly, I tried appending the script to the DOM:

    var script = document.createElement("script");
    script.src = "./web3.min.js";
    document.head.appendChild(script);
    

Unfortunately, none of these methods resolved the issue for me. While I understand the security constraints, I am still looking for a viable solution to include web3 in my extension.

Answer №1

In my opinion, utilizing web3.js in your background script is feasible by installing the package and importing the compact version it includes.

npm i --save web3
import Web3 from 'web3/dist/web3.min.js';
...
const web3 = new Web3(Web3.givenProvider || provider);
const contract = new web3.eth.Contract(abi, contractAddress);

If you encounter issues, referring to the web.js project README might offer additional troubleshooting guidance.

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

Changing the size of a responsive navigation bar with React and adjusting it based on the window.scrollY position switches between collapsed and un

I'm struggling to create a responsive navbar that automatically adjusts its size once it surpasses the height of the navbar (currently set at 80px). However, when I scroll to around the 80px mark, it starts flickering between the collapsed and expande ...

In Photoshop scripting, trying to manipulate an undefined object is like trying to find

I am facing an issue in Photoshop while trying to create a grommet using a script. The error message I receive is: Error: undefined is not an object line 63 ( grommetMarkL = printMarksLayer.pathItems.ellipse( -(spacingY), spacingX, grommetSize, gromm ...

Creating a JavaScript function to download specific sections of an HTML page

Currently, I am implementing PHP MySQL in my HTML page. I have already utilized several div elements in my page. I successfully created a print button that prints a specific div on the page. Now, I am looking to add a download button that will allow users ...

Differences between JavaScript array manipulation using the split(" ") method and the spread operator

I'm currently attempting to determine if a given sentence is a palindrome, disregarding word breaks and punctuation. The code snippet that utilizes cStr.split(" ") DOES NOT achieve the desired outcome. Although it splits on whitespaces (&qu ...

Display a tooltip when the user hovers over the column name of a BootstrapVue table

I am currently working with a bootstrap-vue table that has the following structure; https://i.sstatic.net/bfS9u.png Below is the code for setting up the table; <template> <div> <b-table striped hover :items="items" :fields= ...

manipulating elements of an array within a .map method

i am stuck with a json exporting database. it generates json data in the following format. {"Drinks":[ { "name":"name", "discription":"discription", "image":"image", "ingredients&qu ...

What is the best way to transfer data from one worker to all the others in node.js?

Upon node boot up, I initialize an in-memory JavaScript object. This node app runs on multiple cores using the cluster module. When an HTTP request is received, it is handled by one of the worker threads which then modifies the value of the JavaScript ob ...

Ways to limit date selection with JavaScript or jQuery

On my webpage, I have two date fields: fromDate and toDate. My goal is to prevent submission if the difference between the dates is more than 7 days. https://i.sstatic.net/65LLH.png Despite implementing a script for this purpose, it doesn't seem to ...

Inject data from ajax into the body of the html document

Is it possible to retrieve values from an ajax call and insert them into the body of an HTML document? Here is an example: function check() { $.ajax({ url : '/check', datatype : 'json', async ...

The issue with the Ajax infinite scrolling gallery is that it repeatedly displays the same images multiple times

I'm currently working on developing a straightforward gallery page that dynamically adds elements as you scroll to the bottom. To achieve this, I am using Django to render an HTML snippet from the backend and then utilizing JavaScript to append it to ...

Stop React Form from automatically submitting by preventing automatic submission

I am currently facing an issue with a form that includes a rich text editor and a submit button. The problem arises when the style buttons in the rich text editor are clicked, causing the form inputs to submit unintentionally. My goal is to prevent this b ...

What is the best method for choosing HTML "ids" that are generated automatically by DevExpress controls using JavaScript DOM manipulation?

How can I create a pop-up that displays unique information for each of the hundreds of html divs with a common class but individual ids generated by DevExpress Controls? I have a large number of automatically generated html div "ids" and I'm looking ...

I am unable to generate a vite application within WSL

My system is running node version 10.19.0 and npm version 6.14.4. Whenever I try to run create-vite@latest client, I encounter the following error: npx: installed 1 in 0.79s /home/victor/.npm/_npx/86414/lib/node_modules/create-vite/index.js:3 import &apos ...

I want to display events from my database table on their corresponding dates using JavaScript and jQuery. How can I achieve this?

Using the FullCalendar plugin, I attempted to achieve a specific functionality, but unfortunately fell short of my goal. Below is the snippet of my scripting code: $('#calendar').fullCalendar({ //theme: true, header: { ...

Is there a way for me to incorporate a JavaScript file from another JavaScript file in HTML, even if it's just one line below?

It seems that the issue of using a function or a variable from file1 in file2 is not working as expected: <head> <script src="file1.js"></script> <script src="file2.js"></script> </head> Since file2 ...

Ways to navigate to a new page using jQuery Mobile

As a newcomer to jquery mobile, I am still learning how ajax handles page transitions, and I suspect the issue may be related to that. In my jqm / phonegap app, I have set up multiple pages. The homepage checks if the user is logged in by retrieving membe ...

What measures can be taken to block Javascript from retrieving PHP cookie information?

(Extracted from an interview) Identify the correct answers from the list below: Implement the httponly parameter when creating the cookie The user needs to disable Javascript support This setting is related to cookies in the browser Restrict access to t ...

Issue with CORS on Next.js static files leading to broken links on version 10.1.4

Currently, my Nextjs application is fetching its static files from Cloudfront. During deployment, I upload the /static folder to S3. After updating to version 9, I encountered a strange problem where some of my CSS files are triggering a CORS error: Acces ...

Conceal element when unchecked

There is a checkbox pre-selected labeled "Use profile address" with the address displayed below. If the customer unchecks the checkbox, the address that was shown before will disappear and a new input field for adding a different address will appear. I a ...