0

I recently discovered the chrome extension development and got stuck with the runtime.excuteScript method, the callback in 3rd argument systematically returns me an empty object ...

For brevity, I will spare you all of my manifest.json(v2):

manifest permissions:

  "permissions": [
    "storage",
    "cookies",
    "tabs",
    "background",
    "activeTab",
    "<all_urls>",
    "*://*/*"
  ]

manifest content-script:

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "run_at": "document_end",
      "js": ["js/content-script.js"]
    }
  ]

My goal is to send the content of the localStorage to my extension.

pop-up.js:

chrome.tabs.executeScript(
  null, 
  { file: "js/content-script.js" },
  (result) => {
    if(result) console.log( " Result of content-script:",result ) 
    else console.log(" No content-script, no result")
  }
);

content-script.js:

localStorage;

output in the console of extension:

 Result of content-script: Array(1)
   ▶︎ 0: {} 
   length:1
   ▶︎ __proto__: Array(0)

Please make this a wonderful evening by explaining the mistake to me! Thank you!

Karleen-Bx
  • 47
  • 7
  • localStorage is not an array so it doesn't have `length`. Your entire content-script.js should be just `localStorage`, nothing else. – wOxxOm Apr 29 '21 at 14:33
  • To verify what's actually being returned it's better to use devtools of the popup, which can be opened by right-clicking inside the popup and selecting "inspect". In devtools you can set a breakpoint inside the callback so when it triggers you will see the real value. It should be an array, not an object, and the first element will be the data. If that data is empty it means there's no data in localStorage of the active page. – wOxxOm Apr 29 '21 at 14:37
  • @wOxxOm I modify it in my code, but it's the same result and i'm sure i have datas in local store of my page with a console.log in my content-script thaht return to me Storage {usbl.b947a5295d9a.c.59d7ee81a237: "F/3/T//0//", …} – Karleen-Bx Apr 29 '21 at 14:53
  • If your code modifies the data after console.log then the output will be wrong, which is why you should verify it by using a breakpoint. Alternatively you can use JSON.parse(JSON.stringify(result)) to ensure it's cloned. Anyway, the code is correct so the problem must be something else that's not shown in the question. – wOxxOm Apr 29 '21 at 15:08

2 Answers2

0

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});

▼ pop-up.js:

chrome.runtime.onMessage.addListener((message) => {message.localStorage});
Karleen-Bx
  • 47
  • 7
0

For me, it was because I was returning an unserializable object in my func.

Must return something simple like String or int. The issue is that no exception is thrown, it silently erases the result

Zied Hamdi
  • 2,400
  • 1
  • 25
  • 40