2016-05-04 23 views
0

contentscript.jsChrome擴展:試圖傳遞消息,並且一旦接收到該消息運行一個函數

function createIDArray() 
    { 
     var IDArray = []; 

     IDArray[0] = $('#u_4_0 > span > div').html(); 


     return IDArray; 
    } 

    chrome.runtime.onMessage.addListener(
     function(request, sender, sendResponse) { 
     console.log("This is being received from popup.js"); 
     if (request.greeting == "hello") 
      console.log(createIDArray()); 
      sendResponse({farewell: "goodbye"}); 
      return true; 

     }); 

popup.js

$('#9610').click 
(

    function() 
    { 
     chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
      chrome.tabs.sendMessage(tabs[0].id, {greeting: "This is data."}, function(response) { 
      console.log(response.farewell); 
      }); 
     }); 
    } 
); 

不接收所述兩個腳本之間的任何反應。我的最終目標是在點擊彈出框中的按鈕後,激活內容腳本中的功能。

popup.html

<head> 
    <script type="text/javascript" src="jquery.js"></script> 
    <script src="popup.js"></script> 

</head> 
<body> 
    <button id="9610">Copy SRT Data</button> 
    <button id="1691">Paste SRT Data</button> 
</body> 

的manifest.json

{ 
    "manifest_version": 2, 

    "name": "Task Auto Fill", 
    "description": "This extension shows a Google Image search result for the current page", 
    "version": "1.0", 

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

    "name": "My extension", 
    "background": { 
    "scripts": ["background.js"] 
    }, 
    "permissions": [ 
    "https://our.intern.facebook.com/", 
    "tabs", 
    "activeTab" 

    ], 
    "content_scripts": [ 
    { 
     "matches": ["http://*/*", "https://*/*"], 
     "js": ["myscript.js"] 
    } 
    ] 
} 

回答

0
  1. popup.html移動你的<script>標籤<body>標籤的底部。請注意,目前您正在將它們放入<head>之內,並且執行$('#9610').click()時,<body>未構建,您根本找不到該按鈕。

  2. 更新request.greeting == "hello"在您的contentscript.js。請保持與您發送的數據同步popup.js