Chrome Extension API: chrome.tabs.captureVisibleTab on Background Page to Content Script

丶灬走出姿态 提交于 2019-12-20 03:05:07

问题


My overall goal was to take a screenshot via the background page using:

http://developer.chrome.com/extensions/tabs.html#method-captureVisibleTab

and pass it to the content script so I can use the page's HTML DOM to analyze the screenshot and cut it up the way I would like.

However, I can't seem to pass the dataUrl back to the content script with Message Passing:

http://developer.chrome.com/extensions/messaging.html

I tried JSON.stringify() but to no avail.

This works perfectly fine:

background.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        sendResponse({imgSrc:'hello'});
    }
);

I switch the code to this and nothing gets through:

background.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        chrome.tabs.captureVisibleTab(
            null,
            {},
            function(dataUrl)
            {
                sendResponse({imgSrc:dataUrl});
            }
        )
    }
);

My only proof that the background page is actually taking a screenshot is that I can do

chrome.tabs.captureVisibleTab(null,{},function(dataUrl){console.log(dataUrl);});

and I see

"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAA....etc..."

logged in background.html, which is valid

My question is: How can I send this URL to the content script?

I would prefer not to do all the logic on the background page which can't control anything on the actual visible page.


回答1:


Use chrome.tabs.sendMessage

background page:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        chrome.tabs.captureVisibleTab(
            null,
            {},
            function(dataUrl)
            {
                sendResponse({imgSrc:dataUrl});
            }
        ); //remember that captureVisibleTab() is a statement
        return true;
    }
);

content script

chrome.runtime.sendMessage({msg: "capture"}, function(response) {
  console.log(response.dataUrl);
});


来源:https://stackoverflow.com/questions/18794407/chrome-extension-api-chrome-tabs-capturevisibletab-on-background-page-to-conten

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!