- 
          
- 
                Notifications
    You must be signed in to change notification settings 
- Fork 412
fix: content script is incorrectly invalidated when injected multiple times #1938
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            namukang
  wants to merge
  5
  commits into
  wxt-dev:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
namukang:invalidate-bug
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
      
        
          +39
        
        
          −30
        
        
          
        
      
    
  
  
     Open
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            5 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      7f406fb
              
                fix: use dispatchEvent rather than postMessage to invalidate
              
              
                namukang 3e860a3
              
                refactor: remove option to ignore first event
              
              
                namukang 02db22f
              
                refactor: ignore script start event from self but not other scripts
              
              
                namukang ecee84c
              
                fix: stop old scripts inside frames
              
              
                namukang 3c745a9
              
                feat: invalidate using window.postMessage for backwards compatibility
              
              
                namukang File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In case there's concern that changing from
window.postMessagetodocument.dispatchEventwill change behavior when it comes to other frames: This comment is incorrect becausewindow.postMessageonly sends a message to the targeted window. It doesn't automatically send messages to other frames — you'd need to specifically target those windows in order to send a message.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Doesn't the
*target mean we're sending messages to all frames?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is my main concern. Basically, this class is meant to properly stop and shut down a content script when an extension updates. In production or in development, you will encounter bugs if we don't properly stop ALL the content scripts running on a page. So if in one update, a content script changes from
allFrames: truetoallFrames: false, some scripts running in iframes won't be stopped by using custom events.Because I'm 99% sure targeting
"*"sends a message to all iframes on the page, and any level.Now, that said, the current approach has tradeoffs as well, this race condition you found. If we don't send a message to all frames, then technically those scripts will still stop after they try and use an extension API, only to find that they can't because the context was invalidated after the update.
On a separate note, another thing to consider is that this is a breaking change that will effect all WXT extensions on their next update. We're going to send a custom event, but the old version of the extension will be listening for messages. This could be resolved by continuing to send the message...
Can I get some more context around why you would inject the same script multiple times in quick succession, like from the reproduction? I need more info to decide how likely this race condition is to weigh it against merging this PR and changing the behavior.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
window.postMessageand iframesTargeting
"*"doesn't send a message to all iframes on the page. ThetargetOriginparameter ofwindow.postMessagespecifies which origin is allowed to receive the message.In order to send a message to an iframe, the iframe's window needs to be targeted directly: e.g.
iframe.contentWindow.postMessage(message, targetOrigin);From MDN:
The current code of
window.postMessage(message, "*")simply sends a message to the current window and allows any origin to receive it, but it doesn't send a message to iframes.That means the current approach actually has a bug where content scripts inside iframes are not invalidated at all when the content script is injected again (e.g. when the extension updates).
I've created a video demonstration of the behavior with
allFrames: truewith the current implementation and the fix proposed in this PR: https://www.loom.com/share/a172168ee3744979b949ef8411d126bcBackwards compatibility
I've added to the PR to temporarily continue sending the message via
window.postMessageas well in order to invalidate content scripts from before this change. This makes this change backwards compatible and not a breaking change.For the particular scenario you gave: The new implementation doesn't invalidate content scripts inside iframes when injecting a content script is changed from
allFrames: truetoallFrames: false. But this wouldn't be breaking change since the current implementation doesn't handle that case either. I personally think this is an edge case that's not worth worrying about (at least in the scope of this PR), in the same way that WXT doesn't currently try to invalidate content scripts that were injected in previous versions of an extension but were removed or renamed in the current version. I think it'd be fine to let them stop when trying to use an extension API.Overall, I think this change is worth making because it (1) fixes the bug with content scripts inside iframes not being invalidated and (2) entirely eliminates race conditions with invalidations given the synchronous nature of
document.dispatchEvent.Context for multiple injections
Here's why the content script is injected multiple times in quick succession in my extension (Easy Scraper):
When the user clicks the extension icon to open the popup window, a content script is injected into the current tab and is injected again whenever a new page is loaded in the current tab. The popup window does this by having a listener for
browser.tabs.onUpdatedand checking forchangeInfo.status === "complete"to detect when a new page is loaded.However, there are cases when a page causes
browser.tabs.onUpdatedto fire multiple times withchangeInfo.status === "complete". For example, it's fired with statuscompleteagain when the page sets the hash (e.g.window.location.hash = "section") or changes the URL without reloading the page (e.g.window.history.pushState({}, '', '/new-url');.So there are cases where the initial page load causes
browser.tabs.onUpdatedto fire in quick succession, which causes the popup window to inject the content script multiple times. (There's a check that runs to see if the current tab already has the content script before it tries to inject it, but in this case, that check fails because no content script has been injected yet whenonUpdatedis fired multiple times.)For extensions that dynamically inject the content script using
browser.tabs.onUpdated(as in my case where theactiveTabpermission is used along with a popup), this is a fairly unavoidable scenario.