【问题标题】:Ojbc invoke js error: Can't find variable requireOjbc调用js错误:找不到变量要求
【发布时间】:2018-01-26 15:36:38
【问题描述】:

我对 JS 完全陌生。我在 ios 上开发,我们需要在我们的程序中使用 Web3js。在obj-c中调用js函数就可以了。但是,我使用“require”来导入 Web3js 模块,它会抛出“ReferenceError:找不到变量:require”。发生什么了?我错过了什么吗? 有人可以帮忙吗??非常感谢。

更新:

如果'require'不可用,我如何使用obj-c调用的js中的其他模块?

这是我的代码。

obj-c 代码:

NSString* path = [[NSBundle mainBundle] pathForResource:@"bridge/src/index" ofType:@"js"];
jsFunc = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

JSContext* jsContext = [[JSContext alloc] init];
[jsContext evaluateScript:jsFunc];
JSValue* func = jsContext[@"getAddress"];
JSValue* = [func2 callWithArguments:@[@"0x8730f6ad1c0d387644590966bdbfedba44fe250118df0f97f11190ad5727b312"]];    

js:

function getAddress(prvKey)
{
  try{
      var Web3 = require('../../3rd_party/web3.js-1.0.0');     
      var web3 = new Web3();
      return web3.eth.accounts.privateKeyToAccount(prvKey);
  }
  catch (e)
  {
      return e;
  }
}

【问题讨论】:

  • 你能发布你的代码吗?
  • 我猜测您正在使用 Objective-c 中的直接 javascript 桥,但 require 是仅在 Node.js 运行时中的标准函数。您可能必须以其他方式导入 Web3js 模块。但绝对需要查看您的代码,并让您解释您的设置以了解您要做什么。
  • 我已经更新了我的代码。我正在尝试为我们的私有链开发一个以太坊库。它包括创建原始交易、编码 ABI 以及从私钥获取地址。

标签: javascript objective-c web3js


【解决方案1】:

我用Browserify打包所有模块,然后用webView调用js函数。

这是我的 js 文件,index.js

"use strict"
let Web3 = require('web3.js');
window.Web3 = Web3;

然后使用 Broswerify 打包

browserify index.js -o web3.js

我的html,

<html>
<head>
    <script type="text/javascript" src="web3.js"></script>   
</head>
<body>
    <script type="text/javascript">
        function getAddress(prvkey)
        {
            try
            {
                var web3 = new Web3();
                var account  = web3.eth.accounts.privateKeyToAccount(prvkey);
                return account.address;
            }
            catch (e)
            {
                return e;
            }
        }
    </script>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多