刷新后才在linkedin中查找元素

问题描述 投票:0回答:1

我正在技术学校学习有关浏览器的课程。
我在这方面的知识绝对是0。
我们的任务是创建一个在后台运行的简单 chrome 扩展,当您进入 https://www.linkedin.com/jobs 时,它会不断搜索具有

jobs-apply-button
类的元素。
一旦找到元素,它就会打印它。

所以我找到了哪个元素包含

jobs-apply-button
类。它的应用按钮: enter image description here

所以我创建了以下 chrome 扩展:
manifest.json:

{
  "manifest_version": 3,
  "name": "Job Apply Button Checker",
  "version": "1.0",
  "description": "Logs elements with the class 'jobs-apply-button' every second.",
  "permissions": [
    "activeTab",
    "tabs",
    "webNavigation"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["https://*.linkedin.com/jobs/*"],
      "js": ["content.js"]
    }
  ]
}

背景.js:

chrome.webNavigation.onCompleted.addListener((details) => {
  if (details.url.includes('linkedin.com/jobs')) {
    chrome.scripting.executeScript({
      target: { tabId: details.tabId },
      files: ['content.js']
    });
  }
}, { url: [{ urlMatches: 'linkedin.com/jobs' }] });

content.js:

function checkForJobApplyButtons() {
  const elements = document.querySelectorAll('.jobs-apply-button');
  if (elements.length > 0) {
    console.log('Found jobs-apply-button elements:', elements);
  }
}
setInterval(checkForJobApplyButtons, 1000);

然后我转到 LinkedIn -> 职位 -> 具有该按钮的特定职位。
但一开始它不起作用,控制台上没有记录任何内容。
只有在我刷新页面后它才开始工作。
我尝试了多种 content.js 技术,但总是出现同样的问题。
为什么它只有在页面刷新后才起作用,我该如何修复它?

javascript dom google-chrome-extension
1个回答
0
投票
  1. 从manifest.json中的
    jobs/
    中删除
    matches
    ,因为它是一个现代SPA网站,在内部重用相同的页面,这意味着当您在选项卡中打开该网站的不匹配页面时,
    content_scripts
    注入仅发生一次然后转到匹配的页面。
  2. 删除
    chrome.webNavigation
    ,因为您已经拥有
    content_scripts
  3. 在 Chrome 中重新加载/安装扩展程序后,
  4. 重新注入
    content_scripts
© www.soinside.com 2019 - 2024. All rights reserved.