【问题标题】:Firefox addon requires additional refresh to workFirefox 插件需要额外刷新才能工作
【发布时间】:2020-08-08 03:24:56
【问题描述】:

我已经开始开发一个可以在 Github repo 的package.json 上运行的插件。加载插件时,需要额外刷新页面才能使插件生效,而不是在识别 url 后立即应用边框。

manifest.json

{
  "manifest_version": 2,
  "name": "Border It",
  "version": "0.0.1",
  "permissions": ["activeTab", "tabs", "https://github.com/*"],
  "content_scripts": [
    {
      "matches": ["https://github.com/*/package.json"],
      "js": ["src/scripts/borderify.js"],
    }
  ]
}

borderify.js

document.body.style.border = '5px solid red';

我做错了什么?

【问题讨论】:

  • 您的问题不清楚。听起来您是在说您必须在安装插件后加载页面才能注入内容脚本。这个是正常的。内容脚本仅在页面加载时加载。如果您安装一个新的插件,内容脚本不会加载到现有页面中,除非您专门编写了代码来执行此操作(例如,您在后台脚本中编写的代码,它手动将您的内容脚本加载到现有的匹配选项卡中) .但是,您可能会说安装插件后需要刷新两次,这是意料之中的。
  • @Makyen 这就是发生的事情。 1. 我加载插件并转到 github repo 的 package.json 2. 插件应该显示一个边框,但它没有 3. 我按刷新并显示边框

标签: firefox firefox-addon add-on


【解决方案1】:

GitHub 动态更新页面内容,因此您需要在每个 GitHub 页面 ("matches": ["https://github.com/*"]) 上运行脚本并观察位置变化。这里有更多提示: Event when window.location.href changes

(更新) 基于MutationObserver的示例实现:

{
  "manifest_version": 2,
  "name": "Border It",
  "version": "0.0.1",
  "permissions": [
    "activeTab",
    "tabs",
    "https://github.com/*"
  ],
  "content_scripts": [
    {
      "matches": ["https://github.com/*"],
      "js": ["borderify.js"]
    }
  ]
}
function onLocationChanged() {
  if (/\/package.json([?#]|$)/.test(location.pathname))
    document.body.style.border = '5px solid red';
  else
    document.body.style.border = '';
}
onLocationChanged(); // executed when the page is initially loaded

let lastUrl;

const observer = new MutationObserver(mutations => {
  // executed on any dynamic change in the page
  if (location.href == lastUrl)
    return;
  lastUrl = location.href;
  onLocationChanged();
});
const config = {
  childList: true,
  subtree: true
};
observer.observe(document.body, config);

【讨论】:

  • 所有权限都给了,这在我的后台脚本``` const logHstoryStateDetails = (details) => { console.log(details); }; browser.webNavigation.onHistoryStateUpdated.addListener(logHstoryStateDetails); ``` 但是我收到此错误Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ‘https://collector.githubapp.com/collect’. (Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’). 我该怎么办?
  • 我添加了一个基于MutationObserver 的示例实现。它不应该导致任何跨源请求错误。
猜你喜欢
  • 1970-01-01
  • 2020-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多