Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

listen in content-script and change some elements in Dom #8

Open
husin-sajjadi opened this issue May 2, 2023 · 2 comments
Open

listen in content-script and change some elements in Dom #8

husin-sajjadi opened this issue May 2, 2023 · 2 comments

Comments

@husin-sajjadi
Copy link

Thank you for your sample!
I have a problem with development chrome extension,
Let me explain that:
I have a popup.js and popup.html
also I have a content.js as a content-script
also I have a background.js as a background script

Now, I want to click on a button in popup.js and then listen it in content-script and change some elements in dom.

But I don't receive any data in content script

popup.js
chrome.tabs.query({active: true, currentWindow: true}, async (tabs) => { chrome.tabs.sendMessage(tabs[0].id, {message: 'changeDOM'}); });

content.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { console.log("request"); });

How can I solve it?
Should I use a background service?

Thank you for your response!

@L4CTOSE
Copy link

L4CTOSE commented Jul 25, 2023

🤓🤓🤓🤓🤓🤓🤓🤓🤓

@cdrani
Copy link

cdrani commented Nov 5, 2023

This is due to content script and popup not running in the same context, thus the background script will have to be used a bridge/mediator between them. A good solution would be to make use of a PORT. This is a sample approach to communicate from a popup -> background -> content script. It's similar approach to communicate the opposite way as well.

popup.js

// connect to post
const PORT = chrome.runtime.connect({ name: "popup" })

// use that port to send message on button click (inside click handler)
PORT.postMessage({ action: 'button.click' })

background.js

chrome.runtime.onConnect.addListener(port => {
    if (port.name !== 'popup') return

    port.onMessage.addListener(message => {
        // take action based on the message, such as sending to content script
        chrome.tabs.query({ active: true, currentWindow: true }, tabs => { 
            chrome.tabs.sendMessage(tabs[0].id, message) 
        })
    }
}

content.js

chrome.runtime.onMessage.addListener(message => console.log(message))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants