-2

So I need to pass a textbox value (in popup.html) to my content script when a user clicks submit in popup.html. I read many tutorials but I couldn't really understand what they did.

popup.html:

<!DOCTYPE html>
<html>

<body>

<form>
    <input type="text" placeholder="MCM Username" id="username"><br>
    <input type="checkbox" name="vehicle" value="Bike" checked> ON?<br>
    <input type="submit" placeholder="MCM Username" id="sbBtn">


</body>
</html>

manifest.json:

{
    "name": "MCMRainbowName",
    "manifest_version": 2,
    "version": "1.0.0",
    "description": "Turn your name into a rainbow color on MC-Market.",
    "browser_action":
    {
        "default_icon": "icon.png",
        "default_popup": "onoff.html"
    },

    "content_scripts":[
        {
            "matches":["http://mc-market.org/*", "https://mc-market.org/*"],
            "js": ["rainbow.js"]
        }
    ]
}

rainbow.js (my content script):

var username = "RaghavJhavar";

setInterval(function() {
    var elements = document.getElementsByTagName("span");

    for(var i = 0; i < elements.length; i++){
        if(elements[i].innerText == username /*|| elements[i].innerText == "RaghavJhavar"*/){
            document.getElementsByTagName("span")[i].setAttribute("class", "style21");
        }
    }
}, 1000);

When the user clicks "Submit" on the popup.html, how can I send the textbox value where id="username" to rainbow.js? I want the variable username in rainbow.js to equal the textbox value with id 'username' in popup.html.

Can you please explain how to do it too?

Thank you very much.

RaghavJhavar
  • 29
  • 1
  • 5
  • Possible duplicate of [Chrome Extension - Message Passing from Popup to Content Script](http://stackoverflow.com/questions/6108906/chrome-extension-message-passing-from-popup-to-content-script) – Makyen Dec 07 '16 at 17:16

1 Answers1

0

In the popup script use chrome.runtime.sendMessage https://developer.chrome.com/extensions/runtime#method-sendMessage to send message to the content script

In the content script use chrome.runtime.onMessage https://developer.chrome.com/extensions/runtime#event-onMessage to receive a message from background script

Please read documentation Message Passing

belykh
  • 1,109
  • 10
  • 25