将Javascript消息从content.js发送到background.js
将Javascript消息从content.js发送到background.js
我阅读了一些chrome文档并使此基本示例工作。
现在我想根据发生的事件进行请求。该事件被触发并且contentUpdateData()运行,但是函数内的chrome.runtime.sendMessage
似乎无法工作。有什么想法吗?
/* content.js */ var data = [] chrome.runtime.onMessage.addListener( function(request, sesnder, sendResponse) { if (request.message === 'popupClicked') { contentUpdateData(); } } ) function contentUpdateData() { console.log('Code works up to here. Button clicked in popup.html, recieved in content.js. Need to get info from background.js') chrome.runtime.sendMessage({greeting: "hello"}, function(response) { console.log(response.farewell); data = response.data }); }
/* background.js basic example from chrome */ chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension"); if (request.greeting === "hello") sendResponse({farewell: "goodbye", data: null}); } );
admin 更改状态以发布 2023年5月23日
你需要从backgroundjs中的事件监听器中返回true
。这将使sendResponse()
免受垃圾回收机制的威胁。\n
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { if (request.greeting === "hello") sendResponse({ farewell: "goodbye", data: null }); // VERY IMPORTANT return true; });