Automatically jump to a certain part of a WebView

冷暖自知 提交于 2020-01-06 15:51:29

问题


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:

<webview onLoad="window.scroll(0, 150)" class="test" src="http://example.co.uk/test.aspx"></webview>

But it seems that would be far to easy. I'm not convinced its even possible.

Thanks


回答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.



来源:https://stackoverflow.com/questions/39894014/automatically-jump-to-a-certain-part-of-a-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!