简体   繁体   中英

For chrome extension, how can main.js call function from popup.js?

I have extracted username and password(main.js) from webpages and try to store them in indexeddb(popup.js). So far, the popup.html(popup.js) can store username and password manually. I want to call the function in popup.js when there are username and password. Thank you very much.

Function in main.js

if (username && password)    
{            
    if(confirm("Store domain with username and password?"))      
    {        
        //want to call function test() from popup.js       
    }
    else
    {
    }    
}

Function in popup.js

function test()
{
    alert("function called");
}

manifest.json

{
  "name": "PM Extension",
  "version": "1.0",
  "manifest_version": 2,
  "description": "a Google Chrome extension",
  "permissions": ["tabs"],

  "browser_action": {  
    "default_icon": "icon.png" ,
    "default_title": "PM Extension",
    "default_popup": "popup.html"
  },

  "content_scripts": [
    {
      "matches": ["http://*/*", 
      "https://*/*"
      ],
      "js": ["jquery.min.js", "main.js"],
      "run_at": "document_start"
    }]
}

main.js

chrome.runtime.sendMessage('Your string/ object/ whatever', function(response) {
    console.log(response.farewell);
});

popup.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request === 'What I want to recieve') {
        // Do something
        sendResponse('A response');
    } 
});

See the Massage Passing documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM