Chrome extension - retrieving global variable from webpage

后端 未结 5 1766
离开以前
离开以前 2020-11-22 17:10

I am working on an extension for Chrome. I wish parse the content of the \"original\" Gmail message (the currently viewed message).

I tried to utilize the jQuery.loa

5条回答
  •  孤街浪徒
    2020-11-22 18:08

    A more modern solution for communicating between a chrome extension content_script and the javascript on the page would be to use the html5 postMessage API. Any messages sent to "window" are visible from both the javascript on the webpage and the extension's content_script.

    The extension's content_script.js:

    window.addEventListener('message', function(event) {
        console.log('content_script.js got message:', event);
        // check event.type and event.data
    });
    
    setTimeout(function () {
        console.log('cs sending message');
        window.postMessage({ type: 'content_script_type',
                             text: 'Hello from content_script.js!'},
                           '*' /* targetOrigin: any */ );
    }, 1000);
    

    The javascript running on the webpage:

    window.addEventListener('message', function(event) {
        console.log('page javascript got message:', event);
    });
    
    setTimeout(function() {
        console.log('page javascript sending message');
        window.postMessage({ type: 'page_js_type',
                             text: "Hello from the page's javascript!"},
                           '*' /* targetOrigin: any */);
    }, 2000);
    

    Also see http://developer.chrome.com/extensions/content_scripts.html#host-page-communication

提交回复
热议问题