如何在 Chrome 插件中使用外部 ajax 响应
How to use external ajax response in Chrome Plugin
我的网站中有一个现有文件 ajax,js,它发出 ajax 请求并创建一个全局 JSON 对象,使用该响应的 searchResult。现在我正在创建一个 Chrome 插件,它需要这个 JSON 对象在里面。我有一个插件的内容脚本。 plugin.js 并且我想将对象包含在 plugin.js 文件中。
当我尝试从 plugin.js 中记录 window.searchResult 时,它显示为未定义。
但是当我使用浏览器控制台时,它显示了预期的值。
请帮我解决这个问题。
问题
Chrome 内容脚本和页面自己的脚本位于 isolated worlds。
Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page.
您的代码在控制台中运行,因为您默认在页面的上下文中执行它。要查看扩展程序看到的内容,您需要 .
解决方案 1a
首先,通用解决方案(即使您不控制网页也有效)
有一种方法可以解决此问题,方法是将一些代码直接注入页面的 "world"(或正确称为上下文)。
在 injecting the code, your page-level script needs to communicate with the content script to pass the data. It's possible with custom DOM events 之后(如您所知,DOM 已共享)。页面级脚本发送一个事件,其中包含事件详细信息中的数据。
或者,您可以将数据附加到某个 DOM 节点,例如,一个不可见的 <div>
。
解决方案 1b
既然你说这是你的页面,你可以跳过注入页面的步骤,并在页面自己的代码中准备好一个监听器。
内容脚本发送一个自定义事件来请求数据,页面响应将数据传回,如 1a 中所述。
解决方案 2
理论上,您甚至不需要内容脚本。
您可以使用 "externally_connectable"
mechanism 直接与页面对话。
请注意,页面必须发起对话。
我的网站中有一个现有文件 ajax,js,它发出 ajax 请求并创建一个全局 JSON 对象,使用该响应的 searchResult。现在我正在创建一个 Chrome 插件,它需要这个 JSON 对象在里面。我有一个插件的内容脚本。 plugin.js 并且我想将对象包含在 plugin.js 文件中。
当我尝试从 plugin.js 中记录 window.searchResult 时,它显示为未定义。
但是当我使用浏览器控制台时,它显示了预期的值。
请帮我解决这个问题。
问题
Chrome 内容脚本和页面自己的脚本位于 isolated worlds。
Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page.
您的代码在控制台中运行,因为您默认在页面的上下文中执行它。要查看扩展程序看到的内容,您需要
解决方案 1a
首先,通用解决方案(即使您不控制网页也有效)
有一种方法可以解决此问题,方法是将一些代码直接注入页面的 "world"(或正确称为上下文)。
在 injecting the code, your page-level script needs to communicate with the content script to pass the data. It's possible with custom DOM events 之后(如您所知,DOM 已共享)。页面级脚本发送一个事件,其中包含事件详细信息中的数据。
或者,您可以将数据附加到某个 DOM 节点,例如,一个不可见的 <div>
。
解决方案 1b
既然你说这是你的页面,你可以跳过注入页面的步骤,并在页面自己的代码中准备好一个监听器。
内容脚本发送一个自定义事件来请求数据,页面响应将数据传回,如 1a 中所述。
解决方案 2
理论上,您甚至不需要内容脚本。
您可以使用 "externally_connectable"
mechanism 直接与页面对话。
请注意,页面必须发起对话。