Reputation: 39
I am developing a chrome extension that opens an iframe in the current tab.
I need to be able to highlight some text on the webpage, and have it appear in the iframe.
However, it would be unsafe to simply use postmessage as a malicious website could take advantage of that and spam the iframe.
So, I think, and I could be wrong, that I have to have my executed script transmit the highlighted text to the background script which could then inject some script into my iframe to display the text.
How can I communicate between an executed script (chrome.tabs.executeScript) and the background script?
Thanks
Upvotes: 0
Views: 182
Reputation: 73556
Assuming the iframe points to a file exposed in web_accessible_resources and its src is properly formed e.g. chrome.runtime.getURL('iframe.html')
, this iframe.html will be running in a document with a chrome-extension://
URL which has the same privileges as your background script or browser_action script.
In other words, this iframe script can use the safe extension messaging directly.
iframe.html:
<script src=iframe.js></script>
iframe.js:
chrome.tabs.getCurrent(tab => {
chrome.tabs.sendMessage(tab.id, 'getFrameData', {frameId: 0}, processData);
});
function processData(data) {
console.log(data);
}
content.js:
function createFrame(data) {
const el = document.createElement('iframe');
el.src = chrome.runtime.getURL('iframe.html');
document.body.appendChild(el);
chrome.runtime.onMessage.addListener(function _(msg, sender, sendResponse) {
if (msg === 'getFrameData') {
sendResponse(data);
setTimeout(() => chrome.runtime.onMessage.removeListener(_));
}
});
}
And of course port-based messaging can be used as well.
Upvotes: 1