我有一个带有自己的脚本和变量的网页,我需要执行这些脚本和变量并从我的扩展的 Background.js 中检索返回值。
我明白(我认为!)为了与网页交互,必须通过 chrome.tabs.executeScript 或 ContentScript 来完成,但因为代码必须在原始页面的上下文中执行(为了有范围到脚本和变量),它需要先注入到页面中。
在Rob W 的这篇很棒的帖子之后,我能够调用页面级脚本/变量,但我很难理解如何以这种方式返回值。
这是我到目前为止所得到的......
网页代码(我想与之交互):
<html>
<head>
<script>
    var favColor = "Blue";
    function getURL() {
      return window.location.href;
    }
</script>
</head>
<body>
    <p>Example web page with script content I want interact with...</p>
</body>
</html>
清单.json:
{
  // Extension ID: behakphdmjpjhhbilolgcfgpnpcoamaa
  "name": "MyExtension",
  "version": "1.0",
  "manifest_version": 2,
  "description": "My Desc Here",
  "background": {
    "scripts": ["background.js"]
  },  
  "icons": {
    "128": "icon-128px.png"
  },
  "permissions": [
    "background",
    "tabs",
    "http://*/",
    "https://*/",
    "file://*/",           //### (DEBUG ONLY)
    "nativeMessaging"
  ]
}
背景.js
codeToExec = ['var actualCode = "alert(favColor)";',
                  'var script = document.createElement("script");',
                  ' script.textContent = actualCode;',
                  '(document.head||document.documentElement).appendChild(script);',
                  'script.parentNode.removeChild(script);'].join('\n');
chrome.tabs.executeScript( tab.id, {code:codeToExec}, function(result) {
   console.log('Result = ' + result);
} );
我意识到代码目前只是“提醒”favColor 变量(这只是一个测试,以确保我可以看到它工作)。但是,如果我尝试返回该变量(将其保留为最后一个语句或说“返回 favColor”),则 executeScript 回调永远不会有该值。
因此,这里似乎(至少)三个级别:
- 背景.js
 - 内容脚本
 - 实际网页(包含脚本/变量)
 
...我想知道从第 1 级到第 3 级(以上)并返回值的推荐方式是什么?
提前致谢:o)