这可能是因为Chrome的默认配置不允许Tampermonkey扩展访问某些特定的页面元素。为了解决这个问题,我们可以使用两种方法:
-
在Tampermonkey设置中打开“访问文件网址”选项
打开Chrome浏览器,点击Tampermonkey的图标,选择“选项”,然后选择“脚本”,在“配置模式”中选择“高级”,然后将“访问文件网址”选项打开。这样做可以允许Tampermonkey扩展访问本地文件和页面元素。
-
修改Chrome配置
在Chrome浏览器中输入“chrome://flags/#allow-insecure-localhost”并按回车键。在“不安全的本地主机URL”选项下,选择“启用”,重启Chrome浏览器后,Tampermonkey扩展应该可以访问特定的页面元素了。
下面是一个简单的代码示例,可以检测页面中某个元素的更改,然后在控制台输出一条消息。
// ==UserScript==
// @name Watch for element changes
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Watch for changes to the page and log a message when the target element is modified.
// @author Your name
// @match http://*/*
// @match https://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// Define the target element to watch
const target = document.querySelector('#my-element');
// Create a MutationObserver instance
const observer = new MutationObserver((mutations) => {
// Loop through all mutations
for (const mutation of mutations) {
// Check if the target element was modified
if (mutation.target === target) {
console.log('The target element was modified');
}