在WebView中更改CSS样式

时间:2019-05-08 19:46:28

标签: typescript webview nativescript

我通过NativeScript中的Web查看加载页面,我需要隐藏一些元素块。 在收到的HTML中插入CSS的选项是什么? 还是有什么选择? 我找不到我的问题的答案:c

page.xml //显示页面的XML

<GridLayout class="page-content">
        <Label row="1" text="{{ result }}" style="text-align:center; z-index:99" />
        <WebView row="2" loaded="onWebViewLoaded" id="myWebView" src="{{ webViewSrc }}"
            style="z-index:1">
        </WebView>
 </GridLayout> 

page.ts //我要在其中添加样式的逻辑


export function onDrawerButtonTap(args: EventData) {
    const sideDrawer = <RadSideDrawer>app.getRootView();
    sideDrawer.showDrawer();
}


export function onNavigatingTo(args) {
    const page: Page = <Page>args.object;
    const vm = new Observable();
    vm.set("webViewSrc", "https://m.stoloto.ru/check?int=sitemap");
    vm.set("result", "");
    page.bindingContext = vm;
}
// handling WebView load finish event
export function onWebViewLoaded(webargs) {
    const page: Page = <Page>webargs.object.page;
    const vm = page.bindingContext;
    const webview: WebView = <WebView>webargs.object;
    vm.set("result", "Загрузка...");
    vm.set("enabled", false);

    webview.on(WebView.loadFinishedEvent, (args: LoadEventData) => {
        let message = "";
        if (!args.error) {
        } else {
            message = `Ошибка загрузки, проверьте соединение с интернетом`;
        }

        vm.set("result", message);
    });
}
// going to the previous page if such is available
export function goBack(args) {
    const page: Page = <Page>args.object.page;
    const vm = page.bindingContext;
    const webview: WebView = <WebView>page.getViewById("myWebView");
    if (webview.canGoBack) {
        webview.goBack();
        vm.set("enabled", true);
    }
}
// going forward if a page is available
export function goForward(args) {
    const page: Page = <Page>args.object.page;
    const vm = page.bindingContext;
    const webview: WebView = <WebView>page.getViewById("myWebView");
    if (webview.canGoForward) {
        webview.goForward();
    } else {
        vm.set("enabled", false);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以通过在页面加载后通过JavaScript创建Style元素来注入CSS。

const webView = <WebView>args.object,
    jsStr = `var parent = document.getElementsByTagName('head').item(0);
            var style = document.createElement('style');
            style.type = 'text/css';
            style.innerHTML = ".-bg-blue {background-color: red !important;}";
            parent.appendChild(style)`;

if (webView.ios) {
    webView.ios.evaluateJavaScriptCompletionHandler(jsStr,
        function (
            result,
            error
        ) {
            if (error) {
                console.log("error...");
            }
        });
} else if (webView.android) {
    // Works only on Android 19 and above
    webView.android.evaluateJavascript(
        jsStr,
        null
    );
}

Playground Sample

上面的代码将https://www.nativescript.org/处的蓝色背景变成红色。