【问题标题】:Access to active page html code from chrome extension background.js从 chrome 扩展 background.js 访问活动页面 html 代码
【发布时间】:2013-11-21 19:20:28
【问题描述】:

我无法从我的扩展程序的 background.js 脚本访问活动选项卡(页面)的 html 代码

manifest.json

"background": {
  "scripts": ["jquery.js","background.js"]
},

background.js

chrome.webRequest.onBeforeRequest.addListener(
  function(info) {
    return {redirectUrl: "http://www.mysite.com/script.php?" +
                        "data=" + encodeURIComponent($('#J_Data').text())};
  },
  {
  urls: [
    "http://www.othersite.com/addItems.do*"
  ],
  types: ["script"]
},
["blocking"]);

但是 background.js 无法访问活动页面 html 代码并且 "$('#J_Data').text()" 未定义! 如何使用 background.js 和 jQuery 访问活动页面?

【问题讨论】:

    标签: javascript jquery google-chrome-extension


    【解决方案1】:

    您正在后台脚本的上下文中执行 jQuery,它无法访问页面本身。您将需要考虑使用 chrome.tabs.executeScriptcontent scripts 将代码注入您感兴趣的选项卡。您可能需要做的是将脚本注入选项卡,如果有您感兴趣的链接,@987654323 @ 并将数据存储在 tabIds/urls 的临时索引中,以便在 onBeforeRequest 侦听器中包含和查询该索引。

    【讨论】:

    • 我试过 chrome.tabs.executeScript 但 redirectUrl 在 executeScript 完成之前返回 url。如果我将redirectUrl 放到chrome.tabs.executeScript 回调函数中,chrome 不会使用redirectUrl。现在我使用内容脚本并在使用 redirectUrl 之前获取数据。谢谢。 @亚伯拉罕
    猜你喜欢
    • 2019-12-12
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2017-09-27
    • 1970-01-01
    相关资源
    最近更新 更多