1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > chrome扩展程序获取当前页面URL和HTML内容

chrome扩展程序获取当前页面URL和HTML内容

时间:2020-12-12 09:52:26

相关推荐

chrome扩展程序获取当前页面URL和HTML内容

先交代一下manifest.json中的配置

// 引入注入脚本

"content_scripts": [

{

"js": ["content_script.js"],

// 在什么情况下使用该脚本

"matches": [

"http://*/*",

"https://*/*"

],

// 什么情况下运行【文档加载开始】

"run_at": "document_start"

}

],

{

"permissions": [ "tabs"]

}

1.获取当前页面的URL

可在popup.js中获取(chrome.tabs.getCurrent已经out了,返回值是undefined)

chrome.tabs.getSelected(null, function (tab) {console.log(tab.url);});

2.获取当前页面的HTML内容

content-script.js 是注入标签页内的脚本 popup.js 是弹出框脚本 相互通信的方式sendMessage(msg, callback)、onMeassage(callback)(sendRequest、onRequest已经out了,API不再支持) popup.js:发送消息

chrome.tabs.getSelected(null, function (tab) {// 先获取当前页面的tabID

chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {

console.log(response);// 向content-script.js发送请求信息

});

});

content-script.js:响应消息

var html = document.body.innerHTML;chrome.extension.onMessage.addListener(function(request, sender, sendMessage) {if (request.greeting == "hello")sendMessage(html);elsesendMessage("FUCK OFF"); // snub them.});

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。