执行脚本的方法'executeScript'无法工作 - InAppBrowser

3

在我的应用程序中,我正在尝试使用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); });

为什么代码不能运行并且没有返回回调函数?谢谢。
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本身就是一个promise,所以为了使你的代码正常工作,你必须这样写:
$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); });
});

对我来说没问题,但是如果,例如,我想通过getElementById获取一个元素,如果该元素不存在,回调函数不会触发,也不会捕获回调块,有什么办法吗? - undefined

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");
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接