简体   繁体   中英

Calling a function on popup from background. (Google Chrome Extension)

I'm working in a google chrome extension. I have a function in my popup.js that populates a table update_table . I want to call that function from my background.js that sends the important data. The problem is the the update_table on background.js is not define and if i copy the code into that file dont update the table on popup.html.

popup.js

function update_table(content, morecontent){
  if (!document.getElementsByTagName) return;
      tabBody=document.getElementsByTagName("tbody").item(0);
      row=document.createElement("tr");
      cell1 = document.createElement("td");
      cell2 = document.createElement("td");
      textnode1=document.createTextNode(content);
      textnode2=document.createTextNode(morecontent);
      <!-- ... -->
}

popup.html

<!doctype html>
<html>
<head>
<title>Popup Page</title>
<script src="./popup.js" type="text/javascript"></script>
</head>
<body>
   <table border='1' id='mytable'>
      <tbody>
        <tr><td>22</td><td>333</td></tr>
        <tr><td>22</td><td>333</td></tr>
      </tbody>
   </table>
</body>
</html>

background.js

chrome.webRequest.onCompleted.addListener(
    function(request) {
        update_table(request.type, request.url);
    },
    {urls: ["*://*/*"]},
    ["responseHeaders"]
);

background.html

<!doctype html>
<html>
<head>
   <title>Background Page</title>
   <script src="./background.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>

Read this post , I just answer this for another person.

Your best bet it to look the chrome.extension.* API . I will be posting an example on GitHub some time tomorrow that I can show you.

Hope this helps.

UPDATE

Here you go. This is a socket script I created that allows continuous communication between a background page and a popup. There is an example provided in the README. I currently use this for an extension that passes up to 100 items per instance and it works perfect. :P

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