从内容脚本中,我可以对托管在我的服务器上的REST API进行ajax调用吗?
在构建Chrome扩展的同时阅读博客和一些stackoverflow答案之后,我出于某种原因认为我们无法对服务器托管的REST API进行ajax调用,而托管在托管页面之外的另一个域下。它是否正确?在开发我的扩展时,我错误地在内容脚本上点击了我的扩展UI上的按钮(UI使用内容脚本注入到DOM中)。我没有遇到任何错误。一切顺利。我的测试用例中的主机页面实际上是堆栈溢出的页面,REST API托管在我的 localhost 上。难道是因为api在本地主机上吗?
After reading blogs and some stackoverflow answers while building a chrome extension, I had for some reason thought that we cannot make an ajax call to a REST API hosted on server that comes under another domain than the hosted page. Is this correct? While developing my extension, I mistakenly made a call from a content script on clicking a button on my extension UI (UI is injected into the DOM using content script). I did not ran into any error. Everything went smooth. The host page in my test case is infact a page from stack overflow, and the REST API is hosted on my localhost. Could it be because the api was on local host?
来自Chrome XHR文档:
$ b
From Chrome XHR documentation:
常规网页可以使用XMLHttpRequest对象从远程服务器发送和接收数据,但它们受限于相同的源策略。扩展不限于此。一个扩展可以与远程服务器进行通信,只要它首先请求跨源许可。
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
另外,从内容脚本文档:
Furthermore, from the Content Script documentation:
内容脚本也可以将跨站点XMLHttpRequests作为其父扩展的相同网站[/ b]
Content scripts can also make cross-site XMLHttpRequests to the same sites as their parent extensions [...]
所以你唯一需要的是添加你的API端点来清单中的主机权限:
So the only thing you need is to add your API endpoint to host permissions in the manifest:
"permissions" : [
"*://api.example.com/*"
]