新标签页打开PHP文件注入JS传变量时出现toString未定义错误
问题分析与解决方案
错误根源
你当前代码的核心问题是:injectThis(term).toString()是立即执行了injectThis函数,而该函数没有返回值(默认返回undefined),因此对undefined调用toString()才会抛出Cannot read properties of undefined (reading 'toString')错误。同时,这种写法并没有把函数代码传递给新窗口,而是传递了函数执行后的无效结果。
正确实现方式
方式一:动态嵌入变量值到函数代码中
利用模板字符串将变量term的值直接嵌入到函数代码里,同时传递函数本身的字符串形式:
修改主页面的脚本部分:
<script> var topic='1_1_1_2_anchors_'; $(document).ready(function(){ var theWindow = window.open('index.php'), theDoc = theWindow.document, theScript = document.createElement('script'); var term = "garry"; function injectThis() { $("#input_name").val("${term}"); } // 用模板字符串生成脚本内容,确保函数代码被正确传递 theScript.innerHTML = `window.onload = ${injectThis.toString()};`; theDoc.body.appendChild(theScript); }) </script>
方式二:保留带参数的函数形式
如果需要保留函数接收参数的写法,可以将函数调用封装到window.onload的回调中,同时传递变量值:
<script> var topic='1_1_1_2_anchors_'; $(document).ready(function(){ var theWindow = window.open('index.php'), theDoc = theWindow.document, theScript = document.createElement('script'); var term = "garry"; function injectThis(name) { $("#input_name").val(name); } // 在onload回调中执行带参数的函数 theScript.innerHTML = ` window.onload = function() { (${injectThis.toString()})("${term}"); }; `; theDoc.body.appendChild(theScript); }) </script>
补充说明
两种方式都能确保变量值garry被正确传递到新窗口的输入框中,且依赖window.onload等待新窗口的jQuery和DOM完全加载,避免因元素未就绪导致的赋值失败。
内容的提问来源于stack exchange,提问作者Premlatha
相关产品推荐
相关产品推荐

