Hey everyone!
I’m making a Chrome addon that’s supposed to take whatever text you highlight and throw it into a Google search. It’s working okay on regular websites, but I’m stuck when it comes to Google Docs.
Here’s what I’ve got so far:
// content_script.js
chrome.runtime.onMessage.addListener((req, sender, sendBack) => {
if (req.action === 'grabText') {
sendBack({result: document.getSelection().toString()});
}
});
// background.js
chrome.action.onClicked.addListener(tab => {
chrome.tabs.sendMessage(tab.id, {action: 'grabText'}, response => {
if (response.result) {
let searchUrl = `https://www.google.com/search?q=${response.result}`;
chrome.tabs.create({url: searchUrl});
}
});
});
The problem is, when I try to use this on a Google Doc, document.getSelection()
comes up empty. Any ideas on how to make this work with Google Docs? I’d really appreciate some help!
I encountered a similar issue when developing a Chrome extension for Google Docs. The key is to understand that Google Docs uses a complex structure with iframes. To access the selected text, you’ll need to modify your content script to target the specific iframe containing the document content. Here’s a snippet that might help:
function getSelectedText() {
const iframe = document.querySelector('iframe.docs-texteventtarget-iframe');
if (iframe) {
const selection = iframe.contentWindow.document.getSelection();
return selection.toString();
}
return '';
}
Implement this function in your content script and call it when you need to grab the highlighted text. Also, ensure your manifest.json includes the necessary permissions and content script declarations for Google Docs URLs. This approach should allow you to capture selected text within Google Docs reliably.
I’ve dealt with this exact issue before, and it can be frustrating. The trick is to understand that Google Docs uses a complex iframe structure. You’ll need to modify your manifest.json and adjust your content script to target the correct iframe.
In your manifest.json, make sure you have:
{"all_frames":true,"js":["contentScript.js"],"matches":["*://docs.google.com/*"]}
Then in your content script, try something like this:
function getGoogleDocsSelection() {
const iframe = document.querySelector('.docs-texteventtarget-iframe');
return iframe ? iframe.contentWindow.document.getSelection().toString() : '';
}
Use this function instead of document.getSelection() for Google Docs. This should solve your problem and allow your extension to grab highlighted text from Google Docs. Let me know if you need any clarification!
hey tom, i ran into this prob too. google docs uses an iframe, so ya gotta tweak ur manifest. add all_frames: true
and match *://docs.google.com/*
. that should let ur content script access the right frame. good luck with ur extension!