方法“executeScript”不起作用 - InAppBrowser

问题描述 投票:0回答:4

在我的应用程序中,我尝试使用 InAppBrowser 的executeScript 方法执行一些脚本。请记住我正在使用 Ionic Framework v2,这是我的代码:

browser.executeScript({
            code: `
              $(".rodape.geral table tbody tr:nth-child(2) td:nth-child(1) div:nth-child(1)").css("min-width","auto");
              $(".rodape.geral table tbody tr:nth-child(2) td:nth-child(1) div:nth-child(1) div:nth-child(1)").css("width","auto");
              $(".rodape.geral table tbody tr:nth-child(1) td:nth-child(2) table:nth-child(1)").attr("align","center");
            `
          }).then((e)=>{ console.log('JS adicionado.'); }).catch((e)=>{ console.log('Erro ao adicionar JS. '+e); });

为什么代码不起作用并且不返回回调?谢谢。

cordova angular ionic-framework inappbrowser
4个回答
1
投票

确保此代码位于 inAppBrowser 的

loadstop
事件侦听器中。

需要先加载浏览器视图,然后才能运行 JS。


1
投票

我发现您需要在

loadstop
事件中添加此内容,以便在网页加载后添加脚本或样式。

browser.on('loadstop').subscribe(event => {
  browser.executeScript({
    code : 'your javascript code'
  }).then(() => {
    console.log("in executeScript then()");
  });
});    

0
投票

问题在于

executeScript
本身就是一个承诺,因此要使您的代码正常工作,您必须编写如下内容:

$rootScope.$on(’$cordovaInAppBrowser:loadstop’, function (e, event) {
        browser.executeScript({
            code: `
              $(".rodape.geral table tbody tr:nth-child(2) td:nth-child(1) div:nth-child(1)").css("min-width","auto");
              $(".rodape.geral table tbody tr:nth-child(2) td:nth-child(1) div:nth-child(1) div:nth-child(1)").css("width","auto");
              $(".rodape.geral table tbody tr:nth-child(1) td:nth-child(2) table:nth-child(1)").attr("align","center");
            `
          }).then((e)=>{ console.log('JS adicionado.'); }).catch((e)=>{ console.log('Erro ao adicionar JS. '+e); });
});

0
投票

我在尝试发送简单的 console.log() 时遇到问题。由于很多人可能不会使用 RxJS,我将分享我仅适用于 javascript 的最终解决方案:

var inAppBrowserRef = cordova.InAppBrowser.open('https://<website>', '_blank', 'location=yes');


inAppBrowserRef.addEventListener('loadstop', function (event) {
   
    inAppBrowserRef.executeScript({
        code: `console.log('simple test')`
    }).then(() => {
        console.log("finish");
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.