Utilizing the background page to maintain a value required by an injected JavaScript code

{  
    "name": "coffee",
    "manifest_version":2,
    "version": "1.0",  
    "description": "testing coffee app",  
    "browser_action": {  
       "default_icon": "icon.png" ,
       "default_title": "My Task List",
        "default_popup": "popup.html"
     },
  "background": {
    "scripts": ["background.js"]
  },
     "content_scripts": [{
         "matches": ["http://*/*","https://*/*" ], 
         "js": ["inject.js"], 
         "run_at": "document_end",
         "all_frames": true 
    }],
    "permissions": [   
     "tabs", "http://*/*","https://*/*"  
    ]   
}

manifest.josn

count=1;

background.js

var bgpg=chrome.extension.getBackgroundPage();
if(bgpg)
{
    alert("ok");
    if(bgpg.count>=0){
        bgpg.count=bgpg.count+1;
    }else{
        bgpg.count=0;
    }
    alert(bgpg.count);

}else{alert("NO");}

inject.js.

No changes were made. I managed to access the background value last week, but today I seem to have lost track of what might be causing the issue.

Answer №1

A content script is unable to access

chrome.extension.getBackgroundPage()
, as this is considered too high privilege.

Due to security measures, content scripts have limited access to Chrome APIs according to the Chrome's documentation. Manipulating a background page directly is prohibited since it has full access. Consequently, attempting to do so will result in an error that halts execution of your code.

In spite of these restrictions, content scripts are still able to perform certain actions. They are not allowed to:

  • Utilize chrome.* APIs, except for:
    • extension (including methods like getURL, inIncognitoContext, lastError, onRequest, and sendRequest)
    • [...]

To establish communication with the background page, you must employ Messaging. Alternatively, if your requirements simply involve sharing data, consider utilizing chrome.storage, which offers shared storage between the two components.

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

The functionality of the Youtube API is compromised when adjusting display settings on mobile devices

I've successfully embedded a YouTube player using the js-api, and it's working perfectly. However, I don't want the player to be visible by default. To achieve this, I placed the player inside a div with 'display:none;' set. When I ...

A guide on using wrapAll within an each loop in jQuery

I have a series of div elements in my HTML code: <div class="mainClass class_1"></div> <div class="mainClass class_1"></div> <div class="mainClass class_2"></div> <div class="mainClass class_2"></div> <di ...

I am looking to insert an array of a specific type into a Postgres database using Node.js, but I am unsure of the process

query.callfunction('fn_create_mp_product', parameters, (err, result) => { if (err) { console.log(err) callback(err); } else { if (result.status == 'success') { callb ...

Issue with e2e.js file format in Cypress Support

I am trying to save Cypress screenshots into a report using a support file as recommended in the documentation. However, I keep encountering an error: Your supportFile is missing or invalid: support/e2e.js The supportFile must be a .js, .ts, .coffee file ...

Tips for showing a DialogBox when a blur event occurs and avoiding the re-firing of onBlur when using the DialogBox

Using React and Material UI: In the code snippet provided below, there is a table with TextFields in one of its columns. When a TextField triggers an onBlur/focusOut event, it calls the validateItem() method that sends a server request to validate the ite ...

Is there a way to identify the duplicates within an array of numbers and also determine how many times each number is repeated?

Is there a way to find duplicates in an array that appear two or more times? For example, if I have an array of strings like this: var arrStr = 'i do as as becasue i do as'; function CheckDuplicates(sentence) { let arr = sentence.split(" "); ...

Utilizing Regex to Authenticate a CAGE Code

Our task is to create a RegEx pattern that can accurately validate a CAGE Code A CAGE Code consists of five (5) positions. The code must adhere to the following format: The first and fifth positions must be numeric. The second, third, and fourth position ...

Executing a JQuery click event without triggering a page refresh

I'm dealing with a basic form on a webpage <div class="data-form"> <p>Are you hungry?</p> <form> <label class="radio-inline"><input type="radio" name="optradio" value="yes">Yes</label> ...

comparative analysis: nextjs getServerSideProps vs direct API calls

Trying to grasp the fundamental distinction between getServerSideProps and utilizing useSWR directly within the page component. If I implement the following code snippet in getServerSideProps: export const getServerSideProps = async () => { try { ...

Can we apply query projection to a collection that already includes a $elemMatch projection?

I have a question regarding limiting the fields in a matching subdocument array using the $elemMatch projection. It seems like it returns all fields of the subdocuments that match, regardless of any specified query projections. But is there a way to restr ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...

Problem with Marionette AppRouter compatibility when used with Browserify

app.js module.exports = function () { if (!window.__medicineManager) { var Backbone = require('backbone'); var Marionette = require('backbone.marionette'); var MedicineManager = new Marionette.Application(); Medicin ...

The Challenge with jQuery Radio Buttons

I am currently using jQuery to toggle the visibility of a div element. However, I am facing an issue where the else condition is being executed even when it should not be. I am unsure of what mistake I may have made in my code. Any help would be greatly ap ...

What reasons could be preventing the state from updating correctly in Vuex?

Currently, I am working on a project where I am utilizing vuex along with axios to retrieve data from the backend. The issue arises when I try to access the state - even though the updated state is displayed successfully when I console-log it, there seems ...

Implementing ES6 Angular directives with two-way isolated binding

I'm really struggling to understand how isolating scopes function in my code. Interestingly, everything seems to work fine when I remove the scope part of the directive. Can someone please shed some light on what I might be overlooking? export func ...

Point the direction to nextjs and react native expo web

I am currently working on redirecting a URL to another within my website, specifically in Next.js and Expo React Native Web. While I don't have an actual "About" page, I do have other pages nested under the "about" folder and am aiming to direct any ...

Change the value of the checked property to modify the checked status

This is a miniCalculator project. In this mini calculator, I am trying to calculate the operation when the "calculate" button is pressed. However, in order for the calculations to run correctly in the operations.component.ts file, I need to toggle the val ...

Showing a tooltip in Angular when a button is disabled

<button [disabled]="(!dataConceptSummmaryFlag || dataConceptSummmaryFlag === false) && (!selectedLOBFlag || selectedLOBFlag === false) && (!adsListFlag || adsListFlag === false)" class="lmn-btn lmn-btn-primary" ...

Show the tinymce textbox dynamically

Whenever I select an option from a drop-down list, a set of elements are dynamically inserted into a form on the DOM using ajax. Among these elements are textareas that I want to convert into TinyMCE textareas. In my HTML head section, I have the followin ...

Ensure that the input field requires the first letter to be capitalized and the subsequent letters to be in lowercase

There are numerous ways to capitalize the first letter and make the rest lowercase on Stack Overflow. However, I am looking for a method that can instantly enforce this rule in the input field. Being new to AngularJS, I am currently working with version 1 ...