Get Multiple value in Chrome.tabs.executeScript

2020-05-10 14:39发布

问题:

How to return multiple element's value from Chrome Plugin, tabs.executeScript.

Please suggest in below code.

 chrome.tabs.executeScript(
      targetTab.id,
      {
          code: "var header = {'top':document.getElementsByClassName('top-card')[0].innerHTML;}"
      },
      function (sourceCode)
      {
          myCode = sourceCode;
          chrome.tabs.create({'url': chrome.extension.getURL('popup.html')});
      }
    );

Like here I m getting value of class 'top-card' I also want value of, say, 'footer', 'content' much more many class.

回答1:

chrome.tabs.executeScript can transfer any JSON-ifiable data, including simple objects/arrays.

chrome.tabs.executeScript(targetTab.id, {
    code: '(' + function() {
        return {
            top: document.querySelector('.top-card').innerHTML,
            footer: document.querySelector('.footer').innerHTML,
            content: document.querySelector('.content').innerHTML,
        };
    } + ')()'
}, function(data) {
    var myCode = data[0]; // data is an array, item 0 is the main page, 1.. for frames
    console.log(myCode.top, myCode.footer);
});