首页 > 解决方案 > 如何在 chrome.tabs.executeScript 中执行函数

问题描述

我有这个代码:

chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
       chrome.tabs.executeScript(
           tabs[0].id,
           {
              code:            // HERE I want much more space to write
              'var to_filter = document.querySelector("iframe").contentDocument.querySelector("body").querySelectorAll("tbody")[1].innerHTML; alert(to_filter);' 
           },  
            downloadFiles
          );
   });
});


function downloadFiles(resultsArray){
  
}

我必须在标签内执行很多代码code,然后,我必须向函数发送一个links列表downloadFiles。问题是我无法在该code领域编写所有代码,我想改用一个函数。我怎样才能调用一个函数来执行而不是只写在那一行?

- - - 更新

  chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
       chrome.tabs.executeScript(
           tabs[0].id,
           {
              code:'(${ inContent })()'  // ERROR
              //'var to_filter = document.querySelector("iframe").contentDocument.querySelector("body").querySelectorAll("tbody")[1].innerHTML; alert(to_filter);'
            },
            downloadFiles
          );
          function inContent() {
            alert("test")
          }

   });
});

我得到:VM138:1 Uncaught SyntaxError: Unexpected token '{'在上面的注释行中。

标签: javascripthtmlgoogle-chrome-extension

解决方案


推荐阅读