Skip to content
This repository has been archived by the owner on Mar 16, 2024. It is now read-only.

Selection is lost when executing a script #309

Open
vdegenne opened this issue Jan 19, 2023 · 2 comments
Open

Selection is lost when executing a script #309

vdegenne opened this issue Jan 19, 2023 · 2 comments

Comments

@vdegenne
Copy link

vdegenne commented Jan 19, 2023

Great extension!

Nonetheless I am facing an issue, I try to execute a script but this script needs to get the selection in the page,

const selection = window.getSelection().toString()

Of course this fails because when I am initiating a mouse gesture the text is deselected before the script runs, nothing surprising here.

My solution was to inject a piece of code in every page and will save the selected text on the window object.

window._previousSelection = undefined
document.addEventListener('selectionchange', () => {
  const selection = window.getSelection().toString()
  if (selection) {
    window._previousSelection = selection
  }
})

Nothing fancy, then in the mouse gesture script I try to read the value :

const selection = window._previousSelection

No luck... Now I believe it's because your extension is executing the script in its own world and can't access page window user defined properties.

What can I do?


Note: Maybe we could implement a placeholder for that (%s). I know you are already providing this placeholder for search text actions.

Another solution is to just run the script into the MAIN world.
I tried to check the option Inject JQ because I thought that's what it was, but still not working.

(I could open a PR if you show me what part in your code is responsible for executing a script)

@vdegenne
Copy link
Author

Ok the good news is I found where you guys execute user-defined scripts

chrome.tabs.executeScript({code:config.general.script.script[_script].content,runAt:"document_start"},function(){})

The bad news is your extension is using manifest v2 (v3 is the new norm), therefore AFAIK it's not possible to have access to the main world objects properties.

In manifest v3 we could do:

chrome.scripting.executeScript({
  target: { tabId },
  func: ... // `code` in v2
  world: 'MAIN'
}

Do you think it would be difficult to migrate your code to v3 ?

@vdegenne
Copy link
Author

I found a solution, I opened a PR

#310

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant