首页 > 解决方案 > 将 JSON 对象从后台脚本传递到 chrome 扩展中的内容脚本

问题描述

我的 Chrome 扩展程序的“background.js”文件中有一个 JS 数组。我将 JS 对象转换为 JSON 字符串以将其传递到“content.js”文件中,但无法这样做。我可以帮助我使用从“background.js”文件发送 JSON 对象的代码和从“content.js”文件接收相同对象的代码吗?

// This is the important portion of the code present in the background.js file.
console.log("Inside the buttonClicked function");
var titles = [];
var hrefs = [];
var links = document.getElementsByClassName('uqZtlf x0HGk QRiHXd MymH0d maXJsd');
for (var i = 0; i < links.length; i++) 
{
    hrefs.push(links[i].href);  // capturing urls
    titles.push(links[i].title); // capturing titles
}
jsonObjectLinks = JSON.stringify(hrefs); // converting the js object to the JSON string
console.log(jsonObjectLinks);
var jsonObjectTitles = JSON.stringify(titles);

// I now wish to pass on the jsonObjectTitles to the content.js file

标签: javascriptjsonapigoogle-chrome-extensionmessage-passing

解决方案


推荐阅读