createElement(script)/ appendChild如何调试添加的脚本?

时间:2018-06-18 14:41:47

标签: javascript debugging google-chrome-devtools firefox-developer-tools

require "rails_helper.rb"

RSpec.describe "Sign in page" do
    it 'displays the page intention' do
        visit('/mars')
        expect(page).to have_content 'Sign in with Google'
    end
    it 'fills in user information' do
       find(:xpath, '//*[@id="identifierId"]', visible: false)
    end
end

我正在添加这样的脚本,请注意没有 var js = document.createElement("script"); js.type = "text/javascript"; js.innerHTML = layout[i].text; document.body.appendChild(js); ,而是src,而是根据需要使用innerHTML获取脚本。不幸的是,该脚本不会出现在开发工具中,不会出现在Chrome中,也不会出现在Firefox中。

如何从源字符串追加脚本,以便我仍然可以在devtools中调试它?

1 个答案:

答案 0 :(得分:1)

为了能够在Chrome中调试动态添加的脚本,您需要在要调试的脚本末尾添加//#sourceURL = test_file_name.js,如下所示

var js = document.createElement("script");
js.type = "text/javascript";
js.innerHTML = layout[i].text + "//# sourceURL=test_file_name.js";
document.body.appendChild(js);

现在,如果您在开发控制台中打开源选项卡,您将在(无域)部分(通常)下找到test_file_name.js。我刚刚在Chrome版本67.0.X中验证了它。

我相信同样适用于Firefox,

也请参阅这些链接,

Chrome Dev Tools

sourceMappingURL and sourceURL syntax changed

更新 这在firefox中不起作用。为此问题创建了几个错误,但到目前为止还没有修复,script tag using sourceURL doesn't appear in debugger sources pane

相关问题