如何在Chrome扩展的后台脚本中连接到mongoDB?

1dkrff03  于 10个月前  发布在  Go
关注(0)|答案(1)|浏览(180)

嗨,我是Chrome扩展开发的新手,我目前正在尝试在Mv3中制作一个扩展,它使用内容脚本从工作网站收集一些信息,并在单击扩展按钮时通过后台脚本将其发送到mongoDB集合。
我遇到的问题是mongoDB连接。从基于标签页所在网站收集信息,到按下按钮时将其传递到后台脚本,所有操作都已经正常工作。但当我尝试使用mongoDB时,我遇到了错误。导入后mongoDB的设置代码直接来自他们的文档。
我通过在这里寻找类似的问题意识到,你不能在后台和内容脚本中以常规的方式导入外部库,因为它们在浏览器中有不同的上下文,在搜索了一段时间后,我发现了这个solution/workaround。我试图实现第一个解决方案,所以我添加了“type”:“模块”然后我尝试使用常规的import语句将其导入background.js。目前我得到的错误是**“获取脚本时发生未知错误”**。
我不知道我哪里做错了,我会很感激任何帮助解决这个问题。谢谢。
我在扩展文件夹中使用了“npm init”和“npm install mongodb”来获取所需的文件。以下是我到目前为止的代码:manifest.json:

{
  "manifest_version": 3,
  "name": "Extension",
  "version": "0.1",
  "content_scripts": [
      {
          "matches":[
              "*://www.linkedin.com/jobs/view/*",
              "*://www.monster.com/job-openings/*",
              "*://ca.indeed.com/viewjob*"
          ],
          "js": ["content.js"]
      }
  ],
  "background": {
      "service_worker": "background.js",
      "type": "module"
  },
  "action": {
      "default_icon": "bg.png"
  },
  "permissions": ["scripting", "tabs", "activeTab", "storage"]
}

字符串

content.js:

console.log("Chrome extension runnin")

//Properties 
let appSchema = {   // fields
...
}

let temp = appSchema;

let validWebsite = false;

//Triggers
function linkedInTrigger(){   //logic to extract temp info from LinkedIn
...
}
function monsterTrigger(){    //logic to extract temp info from monster
...
}
function indeedTrigger(){     //logic to extract temp info from indeed
...
}
function triggerControl(){    //logic to pick correct trigger
...
}   

if (document.readyState != 'loading') {
    console.log('document is already ready, just execute code here');
    triggerControl();
} else {
    document.addEventListener('DOMContentLoaded', function () {
        console.log('document was not ready, place code here');
        triggerControl();
    });
}

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.status === "pressed")
      console.log("received message in content. Message : "+request.status);
      sendResponse(temp);
  }
);

background.js:

console.log("bg script running")

import { MongoClient, ServerApiVersion } from './node_modules/mongodb/mongodb';

const uri = "mongodb+srv://<username>:<password>@cluster1.abc.mongodb.net/?retryWrites=true&w=majority";
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  }
});
async function run() {
  try {
    // Connect the client to the server (optional starting in v4.7)
    await client.connect();
    // Send a ping to confirm a successful connection
    await client.db("admin").command({ ping: 1 });
    console.log("Pinged your deployment. You successfully connected to MongoDB!");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);


chrome.action.onClicked.addListener((tab) => {
  
  (async () => {
    const [tab] = await chrome.tabs.query({active: true, lastFocusedWindow: true});
    const response = await chrome.tabs.sendMessage(tab.id, {status: "pressed"});
    console.log("message passed")
    console.log(response)
  })();

});

7eumitmz

7eumitmz1#

**首先,**node_modules文件夹是在您的本地机器上创建的,并且它不会被将要安装和使用您的插件的人访问。因此,您需要使用Browserify,Webpack或Rollup等工具从您的node_modules依赖项中生成一个background.js(文件可以命名为任何名称)文件。然后像这样将其导入background.js

import { MongoClient, ServerApiVersion } from './bundle.js';

字符串
生成Weblog.js是一次性的活动,这个Weblog.js将与您的扩展和而不是node_modules文件夹一起提供。

**其次,**您所关注的链接似乎是从Node.js连接Mongodb,此外,我从来没有见过前端应用程序(包括分机)直接与数据库对话。这可能是有害的,因为任何人都可以接管你的数据库。所以理想情况下,你需要一个后端层,它公开一个API,连接到实际的数据库并对其进行更新。你的扩展应该只调用这个API,需要保存到DB的数据。

但我理解你可能不想写整个后端层,因为你的用例很简单,因此,您可以使用MongoDB's atlas api。这将为您提供开箱即用的API,用于更新您的数据库。您只需要担心如何创建API(Atlas提供)从Chrome扩展中点击按钮,Atlas将负责在DB中更新它。这样,您的DB不会暴露,您将有更多的控制权。如果需要,它沿着身份验证和授权。

相关问题