'How do I send messages from a react app to my chrome extension?
I am trying to send session data in the form of a message from my React app to a chrome extension (MV3). According to the documentation, I should be using
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
function(response) {
if (!response.success)
handleError(url);
});
However, doing so gives me the following error: TypeError: Cannot read property 'sendMessage' of undefined
Is there any way to resolve this? I've added /*global chrome*/
at the top of my file which got rid of the chrome undefined
error, but now it's runtime that's undefined.
manifest.json:
"action": {
"default_popup": "popup.html",
"default_icon": "icon-34.png"
},
"permissions": ["storage", "tabs", "activeTab" , "scripting"],
"chrome_url_overrides": {
"newtab": "newtab.html"
},
"externally_connectable": {
"ids": ["extension_id"],
"matches": ["http://localhost:3001/"]
},
App.js (of the react app):
import React from 'react'
import { useState } from 'react'
import logo from './logo.svg';
import './App.css';
import { Auth } from 'aws-amplify';
const App = () => {
function test() {
const extensionId = 'extension_id';
const session = "session";
chrome.runtime.sendMessage(extensionId, session,
function(response) {
console.log(response);
});
}
const [loggedIn, setLoggedIn] = useState(false)
const signInHandler = (event) => {
test();
}
return (
<div>
<button onClick={signInHandler}>Sign in</button>
</div>
)
}
Listener in Background.js:
chrome.runtime.onMessageExternal.addListener(
function (request, sender, sendResponse) {
if (request.session) {
console.log(request);
}
sendResponse("OK");
});
Solution 1:[1]
You have to use https instead of http, chrome.runtime api is only exposed to secured webpages.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pfust75 |