Git Product home page Git Product logo

axios-chrome-messaging-adapter's Introduction

axios-chrome-messaging-adapter

⚠ Deprecated: this project is no longer needed when using Chrome Manifest v3. It is recommended to switch from Manifest v3 as v2 is currently phasing out.

Axios adapter to pass the requests to a Chrome Extension background script. Useful to avoid CORB in content scripts.

More informations about CORB here and here.

Getting Started

Prerequisites

This axios adapter is only intended to be used in Chrome extensions, it simply forwards axios requests to the background script, using the chrome.runtime.sendMessage(...) API.

Installation

With npm (or yarn)

$ npm install --save axios-chrome-messaging-adapter
$ # Or
$ yarn add axios-chrome-messaging-adapter

With a CDN

Axios must be available as a global object so you'll need to import it from a CDN too, we use unpkg here as an example.

<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/axios-chrome-messaging-adapter.min.js"></script>

Quick start

If you are using a bundler, like webpack or rollup:, you'll just need to require the lib. If you are using a CDN, the lib will be available under window.axiosChromeMessagingAdapter.

In your background script:

import axios from 'axios';
import { registerMessageHandler } from 'axios-chrome-messaging-adapter';

// register the adapter message hanlder
registerMessageHandler();

In your content script:

import axios from 'axios'
import { adapter } from 'axios-chrome-messaging-adapter'

// tell axios to use the adapter for this request
const axiosInstance = axios.create({
  adapter,
  ... // the rest of your configuration :)
})

Known limitations

The adapter is currently incompatible with the following axios parameters:

  • paramsSerializer
  • onUploadProgress
  • onDownloadProgress
  • cancelToken
  • transformRequest (axios 0.19+)
  • transformResponse (axios 0.19+)

This limitation is due to the fact that only scalar values can pass through the chrome messaging API, making these callbacks functions unavailable for the moment.

If one of these options is used, it will be ignored and the content script will emit a warning.

Usage with Chrome Manifest V3

When using this adapter with a chrome extension using Manifest V3, XMLHttpRequest isn't available in the service worker (former background script) so the default axios adapter won't work…

To solve this issue, you have to specify a custom adapter that works in this context. I recommend using @vespaiach/axios-fetch-adapter.

import axios from 'axios';
import { registerMessageHandler } from 'axios-chrome-messaging-adapter';
import fetchAdapter from '@vespaiach/axios-fetch-adapter';

// register the adapter message handler and use the custom adapter
registerMessageHandler({ adapter: fetchAdapter });

Development

Clone the project to the directory and install dependencies

$ git clone https://github.com/dzetah/axios-chrome-messaging-adapter
$ cd axios-chrome-messaging-adapter
$ yarn # or npm install
$ npm i --no-save axios # install axios peer dependency

Start typescript compilation in watch mode

$ npm run watch

axios-chrome-messaging-adapter's People

Contributors

arnthors avatar dependabot[bot] avatar myzel394 avatar palmithor avatar sybers avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

axios-chrome-messaging-adapter's Issues

Error when I import { registerMessageHandler } in background.js

Hello !

I have this content script (in src/index.js) file :

import axios from "../dist/axios-client";


async function productStock(url) {
    const { data } = await axios.get(url)
    let availabilityProduct = data.product
    let status;

    availabilityProduct === "no_stock" ? status = false : status = true

    return status
}

let alarmClock = {
    activateNotification: function(e) {
        chrome.alarms.create("myAlarm", { delayInMinutes: 1, periodInMinutes: 1 });
        window.close();
    },

    deactivateNotification: function(e) {
        chrome.alarms.clear("myAlarm");
        window.close();
    },

    setup: function() {
        var a = document.getElementById('alarmOn');
        a.addEventListener('click', alarmClock.activateNotification);
        var a = document.getElementById('alarmOff');
        a.addEventListener('click', alarmClock.deactivateNotification);
    }
};

document.addEventListener('DOMContentLoaded', function() {
    alarmClock.setup();
});

Here is my dist/axios-client.js :

import axios from "axios"
import { adapter } from 'axios-chrome-messaging-adapter'

const client = axios.create({ adapter })

export default client

and my background.js :

import { registerMessageHandler } from 'axios-chrome-messaging-adapter';
registerMessageHandler();

chrome.alarms.onAlarm.addListener(async() => {
    alert("ping")
   // and here i would like to use a content main script function
});

The problem is I can import anything from the background. When i try to import, I have this error :
image

Someone can help me please ?

Thanks in advance !

TypeError: adapter is not a function

Here is my code ES6:

In background:

const axios = require('axios')
const axiosChromeMessagingAdapter = require('axios-chrome-messaging-adapter')
axiosChromeMessagingAdapter.registerMessageHandler()

Content script:

import axios from 'axios'
const axiosChromeMessagingAdapter = require('axios-chrome-messaging-adapter')
const http = axios.create({
adapter: axiosChromeMessagingAdapter
})

export { http }

Error: TypeError: adapter is not a function

Could you fix this?

Bug when using another `chrome.runtime.onMessage` listener

When calling registerMessageHandler within the background script, it adds a new listener with chrome.runtime.onMessage.addListener.

But as there is already a listener (call it B) to handle other types of operation in my code, this causes a bug. The other listener (B) is sending it's response first to contentScript.
In my case, it returns nothing, so I've got the error "Cannot read properties of null (reading 'error')

Moreover, the library uses chrome.runtime api which is callback oriented. In my project, I'm using webextension-polyfill which offers a broader support for other browsers which is not the case of the library and seems to be incompatible

I can't patch-pacakge it neither as the code is minified.

My temporary solution is to fork and modify the code to add the messageHandler in my own listener (B)

I'd be happy to help find a solution that can work for everybody though

Add unit tests

Some unit tests would be welcome to improve the code quality and reliability.

(e.adapter || a.adapter) is not a function in background script

Hi, I'm experiencing issues using registerMessageHandler() in my background script.

I'm using webpack.

src/index.js

import axios from 'axios'
import { registerMessageHandler } from 'axios-chrome-messaging-adapter'
registerMessageHandler()

chrome.runtime.onMessageExternal.addListener(
    function (request, sender, sendResponse) {
        console.log('received');
        localRequest(`https://jsonplaceholder.typicode.com/todos/1`, {
        }).then((response) => {
            console.log('sending back')
            console.log(response)
            sendResponse(response.data)
            return true;
        }).catch((e) => {
            console.error(e);
            sendResponse({ result: 'error', message: e.message });
            return false;
        });
    });

const localRequest = async (endpoint, headers) => {
    return await new Promise((resolve, reject) => {
        axios.get(endpoint, {
            headers: headers
        }).then((response) => {
            resolve(response.data)
        }).catch((e) => {
            reject({ result: 'error', message: e.message }); //(e.adapter || a.adapter) is not a function
        });
    })
}

Here is my Manifest

{
    "name": "My additions",
    "description": "Extra communication",
    "version": "1.0",
    "manifest_version": 3,
    "background": {
        "service_worker": "main.js"
    },
    "permissions": [
        "storage",
        "activeTab",
        "scripting"
    ],
    "host_permissions": [
        "*://*/*"
    ],
    "externally_connectable": {
        "matches": [
            "*://*.domain.xyz/*"
        ]
    }
}

Thank you for your consideration :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.