zoukankan      html  css  js  c++  java
  • 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);
                else
                    sendMessage("FUCK OFF"); // snub them.
            });
     
     
  • 相关阅读:
    数据库多表查询,左连接(入门)
    让弹出层始终显示在屏幕正中间
    jq中的ajax合集总结
    ajax之$.getScript()
    Jquery遮罩ShowLoading组件
    jquery中prop()方法和attr()方法的区别
    Bootstrap 响应式实用工具
    VS使用技巧
    ubuntu下postgreSQL安装配置
    基础设施即代码(Infrastructure as Code)
  • 原文地址:https://www.cnblogs.com/hjqbit/p/7260110.html
Copyright © 2011-2022 走看看