Skip to content

Commit

Permalink
add external message listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
atav32 committed Apr 16, 2019
1 parent f558ce5 commit 70c730c
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
20 changes: 20 additions & 0 deletions crx/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
});
});

chrome.runtime.onMessageExternal.addListener((request, sender, sendResponse) => {
console.log('%c web message', 'color: #0bb', request, `from ${sender.tab ? sender.tab.url : 'extension'}`);
sendResponse({
answer: 'external send message received',
sender: 'background',
});
});

chrome.runtime.onConnect.addListener((port) => {
console.log('%c on connect', 'color: #b0b', port.name);
port.onMessage.addListener((message) => {
Expand All @@ -19,3 +27,15 @@ chrome.runtime.onConnect.addListener((port) => {
});
});
});

chrome.runtime.onConnectExternal.addListener((port) => {
console.log('%c on connect external', 'color: #b0b', port.name);
port.onMessage.addListener((message) => {
console.log('%c external port message', 'color: #b0b', message);
port.postMessage({
name: port.name,
answer: 'external post message received',
sender: 'background',
});
});
});
2 changes: 1 addition & 1 deletion crx/content.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
console.log('%c content', 'color: #bb0');

const messageContainer = document.querySelector('.App-response-section');
const messageContainer = document.querySelector('.App-response-section .App-response-json');

const port = chrome.runtime.connect({ name: 'content' });
port.onMessage.addListener((message) => {
Expand Down
12 changes: 10 additions & 2 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@ const EXTENSION_ID = 'abhjpphflgkfkmcfphlbonifnaadeecc';
class App extends Component {
constructor(props) {
super(props);
this.response = '';
this.state = {
response: ''
};
}

componentDidMount() {
console.log('%c chrome runtime', 'color: #b0b', chrome.runtime);

this.port = chrome.runtime.connect(EXTENSION_ID, { name: 'web' });
this.port.onDisconnect.addListener((event) => {
console.log('%c port disconnected', 'color: #b0b', event);
Expand All @@ -27,6 +31,8 @@ class App extends Component {
response: message
});
});

// external runtime cannot listen to messages
}

sendMessage = (event) => {
Expand Down Expand Up @@ -91,7 +97,9 @@ class App extends Component {
</Section>
<Section className="App-response-section">
<h2 className="App-section-title">Response</h2>
<p>{JSON.stringify(this.response, null, 2)}</p>
<p className="App-response-json">
{JSON.stringify(this.state.response, null, 2)}
</p>
</Section>
</div>
);
Expand Down

0 comments on commit 70c730c

Please sign in to comment.