每次使用 Google 扩展加载页面时都运行内容脚本吗?
我正在制作一个 Google Chrome 扩展程序。我的扩展当前扩展了内容区域和标题,以便为宝石容器(通知和好友请求所在的位置)中的另一个图标腾出空间,并添加该图标。第一次加载页面时它工作正常,但是当您转到网站上的其他页面然后返回主页时,布局就会变得混乱。
由于这不是代码问题(因为它在第一次加载页面时工作正常),因此我想知道是否有一种方法可以在每次加载页面时运行内容脚本。这可能吗?或者我可以在 Facebook 每次使用不同的方法加载时将我拥有的 Javascript 注入 Facebook 中吗?
I'm making a Google Chrome extension. My extension currently extends the content area and header to make room for another icon in the jewel container (where notifications and friend requests are) and adds the icon. It works fine when the page is first loaded, but when you go to a different page on the site and then back home the layout gets screwed up.
Since this isn't an issue with code (as it works fine the first time the page is loaded), I'd like to know if there's a way to run a content script every single time a page is loaded. Is this possible, or can I inject the Javascript I have into Facebook every time it loads with a different method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我了解,每次加载页面时,您的代码都会正确注入,但是当用户选择不同的选项卡然后返回时,您需要代码再次运行吗?
查看页面可见性 API。您应该能够侦听
visibilitychange
事件并再次运行您的代码。As I understand it your code properly gets injected every time a page loads but when a user selects a different tab then returns you need the code to run again?
Have a look at the Page Visibility API. You can you should be able to listen for the
visibilitychange
event and run your code again.我找到了解决此问题的方法,即使用
setInterval()
每毫秒运行一次代码(或者至少是不总是运行的代码)。显然,除非我误解了,Chrome 在每个浏览器会话中运行一次代码,因此使用
setInterval()
是最好的选择。不过,奇怪的行为是 Chrome 曾经运行过我的部分代码,然后除非满足某些情况,否则就不再运行了。不过,
setInterval()
在这种情况下创造了奇迹。I've found a way around this by using
setInterval()
to run the code (or at least the code that wasn't always running) every millisecond.Apparently, unless I misunderstood, Chrome runs the code once per browser session, so using
setInterval()
is the best alternative. Though, the strange behavior was that Chrome was running part of my code once, and then wasn't after that unless certain circumstances were met.setInterval()
worked wonders in this case, though.您应该将该脚本添加为清单文件中的内容脚本。每个浏览器会话仅执行一次后台页面。
清单:
内容脚本文件(go.js):
PS:此方法不适用于 Chrome 内部页面...
You should add the script as a Content script at the manifest file. Background pages are only executed once per browser session.
Manifest:
Content script file (go.js):
PS: This method doesn't work on Chrome internal pages...