Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/450.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么chrome.tabs.executeScript方法的回调结果总是返回空对象?_Javascript_Google Chrome_Google Chrome Extension_Callback_Execute Script - Fatal编程技术网

Javascript 为什么chrome.tabs.executeScript方法的回调结果总是返回空对象?

Javascript 为什么chrome.tabs.executeScript方法的回调结果总是返回空对象?,javascript,google-chrome,google-chrome-extension,callback,execute-script,Javascript,Google Chrome,Google Chrome Extension,Callback,Execute Script,我最近发现了chrome扩展开发,并被runtime.excuteScript方法卡住了,第3个参数中的回调系统地返回了我一个空对象 为简洁起见,我将为您保留所有manifest.json(v2): ▼ 清单权限: “权限”:[ “存储”, “饼干”, “标签”, “背景”, “活动标签”, "", "*://*/*" ] ▼ 清单内容脚本: “内容脚本”:[ { “匹配项”:[“”], “运行时间”:“文件结束时间”, “js”:[“js/content script.js”] } ] 我

我最近发现了chrome扩展开发,并被runtime.excuteScript方法卡住了,第3个参数中的回调系统地返回了我一个空对象

为简洁起见,我将为您保留所有manifest.json(v2):

▼ 清单权限:

“权限”:[
“存储”,
“饼干”,
“标签”,
“背景”,
“活动标签”,
"",
"*://*/*"
]
▼ 清单内容脚本:

“内容脚本”:[
{
“匹配项”:[“”],
“运行时间”:“文件结束时间”,
“js”:[“js/content script.js”]
}
]
我的目标是将本地存储的内容发送到我的扩展

▼ pop-up.js:

chrome.tabs.executeScript(
无效的
{文件:“js/content script.js”},
(结果)=>{

if(result)console.log(“我从未找到解决方案。 但我通过使用以下方法发送数据来解决问题:

▼ content-script.js:

chrome.runtime.onMessage.addListener((message) => {message.localStorage});
▼ pop-up.js:


localStorage不是数组,因此它没有
长度
。您的整个content-script.js应该是
localStorage
,没有其他内容。要验证实际返回的内容,最好使用弹出窗口的devtools,右键单击弹出窗口内并选择“检查”即可打开弹出窗口"。在devtools中,您可以在回调中设置断点,这样当它触发时,您将看到实际值。它应该是一个数组,而不是一个对象,第一个元素将是数据。如果该数据为空,则表示活动页的localStorage中没有数据。@wOxxOm我在代码中对其进行了修改,但结果相同,并且我确信我有数据如果您的代码在console.log之后修改了数据,那么输出将是错误的,这就是为什么您应该使用断点来验证它。或者您可以使用JSON.parse(JSON.stringify(result))无论如何,代码是正确的,所以问题一定是问题中没有显示的其他问题。
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "run_at": "document_end",
      "js": ["js/content-script.js"]
    }
  ]
chrome.tabs.executeScript(
  null, 
  { file: "js/content-script.js" },
  (result) => {
    if(result) console.log( "I never found the solution.
But I got around the problem by sending my data with this methode:

▼ content-script.js:

chrome.runtime.sendMessage({'localStorage' : localStorage});
chrome.runtime.onMessage.addListener((message) => {message.localStorage});