skzao
skzao

Reputation: 1

How to pass variable from popup to content script?

How can i pass a variable from popup.html input to the content script fille? For exemple popup.html

<body>
    <H1>MADE BY SK</H1>

    <input type="text" name="" id="nomeitem">Nome Item
    <input type="button" value="Guarda Valores" id="salvar" onclick="salvar()">
</body>

addtobasket.js

function salvar() {
    item_name = input("nomeitem").value
}

This is just an example i know code is totaly incorrect

Upvotes: 0

Views: 1525

Answers (2)

Sven.hig
Sven.hig

Reputation: 4519

You could use chrome messaging service it will allow you to pass the value after content script is injected or you could use chrome.storage.local

using chrome messaging service

In your popup.js

salvar.addEventListener('click',()=>{
       
        chrome.tabs.query({active:true,currentWindow:true},(tabs)=>{
            chrome.tabs.sendMessage(tabs[0].id,{message: "hello"},(resp)=>{ //specify the message 
                var div=document.createElement('div')
                div.innerHTML=`<p class="text-warning">Notification ${resp.msg}</p>`
                document.body.appendChild(div)
            })
        })
   })

 },false)

In your content.js

chrome.runtime.onMessage.addListener((request,sender,sendMessage)=>{
    value=request.message
//execute your code here 
 sendMessage({msg:'sent'})

Using chrome.storage.local

In your popup.js

chrome.storage.local.set({
    variable: data
},
 function () {
chrome.tabs.executeScript({
        file: "content.js"
    });
});

In your content.js

chrome.storage.local.get("variable", function (data) {
          var getdata=data.variable
          // use getdata in your content script
  chrome.storage.local.remove("variable");// this is optional
});

Upvotes: 1

DCR
DCR

Reputation: 15685

function salvar() {
    var item_name = document.getElementById("nomeitem").value;
    console.log(item_name);
}
<body>
    <H1>MADE BY SK</H1>

    <input type="text" name="" id="nomeitem" >Nome Item
    <input type="button" value="Guarda Valores" id="salvar" onclick="salvar()">
</body>

Upvotes: 0

Related Questions