如何重写网页 chrome.extension.executeScript 的代码

发布于 2024-11-24 17:31:53 字数 735 浏览 3 评论 0原文

我正在编写一个 Chrome 扩展程序,需要能够将代码添加到它正在查看的网页中。现在在我的后台页面中,我有:

chrome.tabs.onUpdated.addListener(function(tabId, info) {
    if (info.status=="complete") {
        chrome.tabs.executeScript(null, {file: "injectme.js"})
    }
})

和注入的脚本 injectme.js 其中包含一个如下所示的函数:

function() {
    if (!document.getElementById('searchforme')) {
        x=document.createElement('script')
        x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
        x.setAttribute('id','searchforme')
        document.appendChild(x)
        alert('it is finished')
    } else {
        alert('so close')
    }
}

我的问题是如何在加载时调用该函数,以便它可以插入脚本写入网页?

I am writing a Chrome extension that needs to be able to add code into the web page it is viewing. Right now in my background page I have:

chrome.tabs.onUpdated.addListener(function(tabId, info) {
    if (info.status=="complete") {
        chrome.tabs.executeScript(null, {file: "injectme.js"})
    }
})

and the injected script injectme.js which contains a function that looks like this:

function() {
    if (!document.getElementById('searchforme')) {
        x=document.createElement('script')
        x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
        x.setAttribute('id','searchforme')
        document.appendChild(x)
        alert('it is finished')
    } else {
        alert('so close')
    }
}

My question is how do I call this function the moment it loads so it can insert the script into a web page?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海夕 2024-12-01 17:31:53

如果我理解你的话:)
您需要做的就是将当前函数扭曲为类似:

 (function () {
  // your code
  if (!document.getElementById('searchforme')) {
      x=document.createElement('script')
      x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
      x.setAttribute('id','searchforme')
      document.appendChild(x)
      alert('it is finished')
    } else {
     alert('so close')
  }
}());

所以它将是一个“立即调用”函数。

If I understood you :)
All you need to do is to warp you current function inside something like:

 (function () {
  // your code
  if (!document.getElementById('searchforme')) {
      x=document.createElement('script')
      x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
      x.setAttribute('id','searchforme')
      document.appendChild(x)
      alert('it is finished')
    } else {
     alert('so close')
  }
}());

so it will be an 'immediate invocation' function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文