内容脚本仅在重新加载/刷新时加载

gla*_*ial 0 javascript google-chrome-extension content-script

这是我第一次创建 Google Chrome 扩展程序,当单击 YouTube 上的建议视频或任何与此相关的视频时,我找不到可靠地让内容脚本运行一次的方法。我试过将“all_frames”设置为true,但这会多次调用脚本。在浏览 YouTube 视频时,是否有一种简单的方法可以让每个视频只运行一次内容脚本?

PS:我使用 YouTube 作为我的主要示例,但其他网站上也存在此问题。是什么原因造成的,我该如何解决?

{//manifest.json
  "name": "Test",
  "version": "0.0.1",
  "content_scripts": [{
      "matches": ["<all_urls>"],
      "js": ["run.js"],
    }],
  "permissions": ["activeTab"],
  "manifest_version": 3
}
Run Code Online (Sandbox Code Playgroud)

——

//run.js
console.log('running');
Run Code Online (Sandbox Code Playgroud)

Max*_*kov 6

问题是 Youtube 动态更新页面,因此在页面内容更改后内容脚本并不总是运行。您需要检测页面 url 是否已更改。

有两种检测内容变化的方法。

解决方案

  1. 使用chrome.webNavigation.onHistoryStateUpdated事件检测内容已更改。

您需要在manifest.json 中为 webNavigation 设置权限:

"permissions": [
    *"tabs", "webNavigation"*
  ]
Run Code Online (Sandbox Code Playgroud)

背景.js

    chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
//Send message to content Script -> Page was changed
//or execute parser from here 
// chrome.tabs.executeScript
});
Run Code Online (Sandbox Code Playgroud)

content.js // 解析你的内容

  1. 使用 Mutation Observers:在您的内容脚本中。

MutationObserver 接口提供了监视对 DOM 树所做更改的能力。

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            // do something with content 
        }
        else if (mutation.type == 'subtree') {
           // do something with content 
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();
Run Code Online (Sandbox Code Playgroud)