Chrome.tabs.sendMessage没有向内容脚本发送消息

时间:2019-12-06 19:13:42

标签: google-chrome-extension

我查看了许多有关使用执行脚本和发送消息以在指定选项卡上执行内容脚本的文章,但是直到我进行硬刷新然后来自服务器的响应后,它才执行内容脚本。内容脚本成功。下面附加的是popup.js文件中单击的按钮的回调函数。

    function buttonClicked() {
    // Get an object for the active tab
  console.log("print dymo has been clicked");
    chrome.tabs.query({active: true, currentWindow: true}, function(tab_array){
        // send a messege to the contentscript that will then scrape the web
    // it will then call the popup.js receiveURL() method with the url it makes
    console.log("Messege sent to conntent script");
    alert("print has been clicked")
    alert(tab_array[0].id)
        chrome.tabs.sendMessage(tab_array[0].id, {getHTML: true}, receiveURL);
    });

内容脚本:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

  // When there is a request (that will come in as true)
 if (request) {

   /*********************************************************************
    IF YOU NEED TO CHANGE THE WEB SCRAPER START HERE
   **********************************************************************/

   // Take out everything in the html before the tag "<label>Job:</label>"
   // Selects only the inner elements between the style row
   var matches = document.querySelectorAll('ul.list-unstyled')
   //Gives us the inner text of the elements of information
   //Gives us an array of all the information split up by new lines
   information = matches[1].innerText.split(/\r?\n/)

   //Iterate ansd store everything in a dictionary split by a : 
   var dict_info = {}
   for (index = 0; index < information.length; index++) { 
    parts = information[index].split(": ")
    ans = ""
    for(i = 1; i < parts.length; i++) {
      ans += parts[i]
    }
    dict_info[parts[0]] = ans 
  }
  var name =  dict_info['Requestor']
  var job = dict_info['Job']
  if (job != undefined) {
    job = job.match(JOB_REGEX)[1]
  }
  var request = dict_info['Request']
  if (request != undefined) {
    request = request.match(REQ_REGEX)[1]
  }
  var file = dict_info["File"]
  if (file.length > 10) {
    file = file.substring(0,file.length-9)
  }
  if (file.length > 20) {
    file = file.substring(0, 20)
  }
  var email = dict_info['Requestor Email']
  var cost = dict_info['Estimated Cost']
  if(cost == undefined) {
    cost = dict_info['Cost']
  }
  if (cost != undefined) {
    cost = cost.match(COST_REGEX)[1]
  }
  name = name.split(" ")
  name = name[0] + "/" + name[name.length-1]
  var url = "https:// test" 


     sendResponse(url);
     return true;
    }
  }
);

0 个答案:

没有答案