chrome扩展之content scripts与web pages 交互

严重吐槽一下CSDN的blog,卧槽,我好不容易写完一篇,点完发表之后就一直loading,然后就让我登陆,然后就特么什么都没有了!!!!!

好了,重新写一遍吧。


发现问题

chrome扩展的content scripts是不能直接访问web pages中的scripts的变量和函数的。一个小需求,让我发现了这个问题,官网描述如下:

Here are some examples of what content scripts can do:
Find unlinked URLs in web pages and convert them into hyperlinks
Increase the font size to make text more legible
Find and process microformat data in the DOM

However, content scripts have some limitatio这里写代码片ns. They cannot:
Use chrome.* APIs, with the exception of:
extension ( getURL , inIncognitoContext , lastError , onRequest , sendRequest )
i18n
runtime ( connect , getManifest , getURL , id , onConnect , onMes

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Chrome扩展content-scripts请求跨域的问题,可以通过在manifest.json文件中添加"permissions"和"web_accessible_resources"字段来解决。具体步骤如下: 1. 在manifest.json文件中添加"permissions"字段,用于声明扩展需要访问的权限。例如: ``` { "name": "My Extension", "version": "1.0", "manifest_version": 2, "permissions": [ "http://www.example.com/*" ], "content_scripts": [ { "matches": ["http://www.example.com/*"], "js": ["content_script.js"] } ] } ``` 以上代码中,"http://www.example.com/*"表示扩展需要访问的域名,"content_scripts"表示扩展需要注入的脚本。 2. 在manifest.json文件中添加"web_accessible_resources"字段,用于声明扩展需要访问的资源。例如: ``` { "name": "My Extension", "version": "1.0", "manifest_version": 2, "permissions": [ "http://www.example.com/*" ], "content_scripts": [ { "matches": ["http://www.example.com/*"], "js": ["content_script.js"] } ], "web_accessible_resources": [ "http://www.example.com/*" ] } ``` 以上代码中,"http://www.example.com/*"表示扩展需要访问的资源。 3. 在content_script.js文件中使用XMLHttpRequest或fetch等API发送跨域请求,代码示例如下: ``` fetch('http://www.example.com/api/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); ``` 以上代码中,fetch方法用于发送跨域请求,并且在响应中获取数据。 需要注意的是,如果要在content-scripts中使用cookie等认证信息,需要在manifest.json文件中添加"permissions"字段,并使用XMLHttpRequest或fetch等API发送带有cookie的跨域请求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值