Skip to content Skip to sidebar Skip to footer

Automatically Jump To A Certain Part Of A WebView

I'm making a Chrome App, and i'm using the web view tag, which is similar to an iframe. Is there a way to load halfway down the webpage that's inside the web view? I have tried:

Solution 1:

Assuming for a moment that code would execute (it won't because of the CSP), window would refer to the app's page, not the embedded page.

You need to execute the code in the context of the embedded page.

If you worked with Chrome extensions before, you would know that the part interacting with web content is called a Content Script.

Apps have a similar concept for <webview> elements. You can either declare in advance which pages should get which content script while they load, or you can explicitly load a content script.

So, suppose you have a file content.js with the following contents (excuse the pun):

window.scroll(0, 150);

Also, assume you have a script app.js running inside your app page, and a variable webview is a reference to the <webview> in there.

Then, you can make the webview execute it:

  • Declaratively, by calling webview.addContentScripts before loading the page (e.g. before setting src from app.js code):

    // Assuming <webview id="wv"></webview>
    var webview = document.getElementById("wv");
    webview.addContentScripts([{
      name: "ExampleRule",
      matches: ["http://example.co.uk/*"], // can be as narrow as you wish
      js: ["content.js"]
    }]);
    webview.src = "http://example.co.uk/test.aspx";
    
  • Explicitly, when the page is already loaded:

    // Assuming <webview id="wv" src="http://example.co.uk/test.aspx"></webview>
    var webview = document.getElementById("wv");
    webview.executeScript({file: "content.js"});
    

It is, of course, possible to make content.js much more sophisticated (for example, receive commands from the app) and/or more precisely control the timing of your operation - but those are at this point generic content script questions for which you can find solutions elsewhere or ask a new question.


Post a Comment for "Automatically Jump To A Certain Part Of A WebView"