Skip to content

promisifying WebFrame.executeJavaScript(InIsolatedWorld) is a breaking change without a workaround #19161

Closed

Description

@bughit

Preflight Checklist

  • I have read the Contributing Guidelines for this project.
  • I agree to follow the Code of Conduct that this project adheres to.
  • I have searched the issue tracker for an issue that matches the one I want to file, without success.

Issue Details

  • Electron Version: v6.0.0-beta.12 x86
  • Operating System: win7 x64 sp1
  • Last Known Working Electron version: v5.0.6

The webFrame execute APIs have always been synchronous (which makes perfect sense, since this is in-process js evaluation), and under the hood they still are, despite now (#17312) returning promises. The callback used to deliver the result synchronously before the method returned.

There is nothing gained and only loss of flexibility when you wrap an actually sync api in a promise. It's trivial for the user to go from sync to promise (Promise.(resolve|reject)) but going from promise to sync is impossible.

So this change (for webFrame) is:

  1. not an improvement
  2. a breaking change for 6.0 (I have code that depends on the synchronous nature of these, which now can't even be fixed without having to become async)

Expected Behavior

existing execute methods should remain sync, they could also be improved by returning the result, in addition to invoking the sync callback (which could be deprecated for later removal)

Actual Behavior

no more sync callback, async promise instead

To Reproduce

  1. launch the following app in 5.0.6
    index.js
    'use strict';
    
    const {app, BrowserWindow} = require('electron'),
          path = require('path');
    
    let win;
    
    app.on('ready', () => {
    
      win = new BrowserWindow({
        width: 1440,
        height: 900,
        useContentSize: true,
        webPreferences: {
          nodeIntegration: false,
          contextIsolation: true,
          preload: path.join(__dirname, 'preload.js'),
        },
      });
    
      win.loadURL('about:blank');
      win.webContents.openDevTools({mode: 'right'});
    
    });
    preload.js
    'use strict';
    
    const {webFrame} = require('electron');
    
    window.evalMainWorldSync = function(code) {
      let result;
      webFrame.executeJavaScript(code, false, res => result = res);
      return result;
    };
  2. In the devtools console for the main world, enter: foo = 1
  3. Switch console context to the Electron Isolated Context
  4. eval evalMainWorldSync('foo')
  5. it prints 1
  6. repeat 1-5 with electron 6.0.0-beta.12
  7. it prints undefined

Activity

  1. bughit commented on Jul 9, 2019

    @bughit
    ContributorAuthor

    @miniak @MarshallOfSound

    I will try to do a pull request for this, could you please comment on what solution you would accept.

    My suggestion is to keep the callback in the webFrame.execute for compat, but deprecate it, which I believe is the standard procedure for removing functionality. Additionally return the eval result, which is a compatible change (before it was undefined)

    I haven't build electron in the new build system, so there may be some delay.

    Since this only regressed in 6.0 I would like to address it there, before the release.

  2. bughit commented on Jul 31, 2019

    @bughit
    ContributorAuthor

    @miniak @MarshallOfSound

    Did a bit more investigating

      enum ScriptExecutionType {
        // Execute script synchronously, unless the page is suspended.
        kSynchronous,
        // Execute script asynchronously.
        kAsynchronous,
        // Execute script asynchronously, blocking the window.onload event.
        kAsynchronousBlockingOnload
      };
    void WebLocalFrameImpl::RequestExecuteScriptAndReturnValue(
        const WebScriptSource& source,
        bool user_gesture,
        WebScriptExecutionCallback* callback) {
      DCHECK(GetFrame());
    
      scoped_refptr<DOMWrapperWorld> main_world = &DOMWrapperWorld::MainWorld();
      auto* executor = MakeGarbageCollected<PausableScriptExecutor>(
          GetFrame(), std::move(main_world), CreateSourcesVector(&source, 1),
          user_gesture, callback);
      executor->Run();
    }
    
    void WebLocalFrameImpl::RequestExecuteScriptInIsolatedWorld(
        int32_t world_id,
        const WebScriptSource* sources_in,
        unsigned num_sources,
        bool user_gesture,
        ScriptExecutionType option,
        WebScriptExecutionCallback* callback) {
      DCHECK(GetFrame());
      CHECK_GT(world_id, DOMWrapperWorld::kMainWorldId);
      CHECK_LT(world_id, DOMWrapperWorld::kDOMWrapperWorldEmbedderWorldIdLimit);
    
      scoped_refptr<DOMWrapperWorld> isolated_world =
          DOMWrapperWorld::EnsureIsolatedWorld(ToIsolate(GetFrame()), world_id);
      auto* executor = MakeGarbageCollected<PausableScriptExecutor>(
          GetFrame(), std::move(isolated_world),
          CreateSourcesVector(sources_in, num_sources), user_gesture, callback);
      switch (option) {
        case kAsynchronousBlockingOnload:
          executor->RunAsync(PausableScriptExecutor::kOnloadBlocking);
          break;
        case kAsynchronous:
          executor->RunAsync(PausableScriptExecutor::kNonBlocking);
          break;
        case kSynchronous:
          executor->Run();
          break;
      }
    }

    So executor->Run(); means kSynchronous which is documented in the source as Execute script synchronously, unless the page is suspended..

    Initially I thought that suspended referred to to tab unloading due to memory pressure and was therefore not applicable, but it may be more complicated. After looking at PausableScriptExecutor::Run

    void PausableScriptExecutor::Run() {
      ExecutionContext* context = GetExecutionContext();
      DCHECK(context);
      if (!context->IsContextPaused()) {
        ExecuteAndDestroySelf();
        return;
      }
      task_handle_ = PostCancellableTask(
          *context->GetTaskRunner(TaskType::kJavascriptTimer), FROM_HERE,
          WTF::Bind(&PausableScriptExecutor::ExecuteAndDestroySelf,
                    WrapPersistent(this)));
    }

    suspended means ExecutionContext::IsContextPaused

      bool IsContextPaused() const {
        return lifecycle_state_ != mojom::FrameLifecycleState::kRunning;
      }

    which means a non FrameLifecycleState::kRunning state

    // The frame lifecycle state.
    enum FrameLifecycleState {
      // State is normal running.
      kRunning,
      // Paused state is used for nested event loops. Does not fire
      // frozen, resumed events on the document.
      kPaused,
      // State is frozen, pause all media. Do not resume media
      // when moving to kRunning.
      kFrozen,
      // State is frozen, auto resume media when moving to kRunning.
      kFrozenAutoResumeMedia,
    };

    I still am not sure if there's a theoretical possibility of a non kRunning state in electron. I suspect a frame could not spontaneously get into such a state. Do you happen to know?

    It would still be valuable to have executeJavaScriptSync and I would like to add it when I have time. If there's any possibility, however remote, of a non kRunning state, it could check for that and throw an error. But practically, always it would just work, synchronously, as before 6.0 changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions